got an error at line "Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);" LatLng.latitude and LatLng.longitude cant be used because not specific values.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{//DirectionFinderListener {
private GoogleMap mMap;
//private Button btnFindPath;
//private EditText etOrigin;
//private EditText etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
// private List<Marker> = new ArrayList<>();
Circle shape;
Marker marker;
//private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
long minDistance = 15;
float[] distance = new float[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//btnFindPath = (Button) findViewById(R.id.btnFindPath);
//etOrigin = (EditText) findViewById(R.id.etOrigin);
//etDestination = (EditText) findViewById(R.id.etDestination);
/*btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});*/
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng hcmus = new LatLng(3.719639, 103.123972); //3.719639, 103.123972
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("IBM CoE")
.position(hcmus)));
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(3.719639, 103.123972))
.radius(10000)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
Toast.makeText(this, "You are in radius location", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}
/*if (destinationMarkers == ) { //equation
Intent main = new Intent(MapsActivity.this, MainActivity.class);
startActivity(main);
}
else { Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}*/
}
How to get current Location latitude and longitude
See the parameter of doc of distanceBetween method. It results distance in meter between two locations and it takes parameters like this,
startLatitude double: the starting latitude
startLongitude double: the starting longitude
endLatitude double: the ending latitude
endLongitude double: the ending longitude
results float: an array of floats to hold the results
As its clearly stated, the first two parameters hold the value of first location object's Latitude and Longitude. In your case, you're referring the default Location object's Latitude and Longitude properties which doesn't represent any location value.
I can see you're already getting current location
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
So, this line should be like this,
Location.distanceBetween(latitude, longitude, circle.getCenter().latitude,circle.getCenter().longitude, distance);
Related
I was trying to make a map activity app which when run, displays user's GPS' location on a map using a marker. However, on running, it just displays the marker in the default location (Sydney) please help. Below is my code.. I have tried a number of ways but all of them still lead me to Sydney. What Im trying to do is for the app to take me directly to my location once run.
Below is my code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_location);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("My Current Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME, MIN_UPDATES_DISTANCE, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
}
Use LocationCallback instead to get your latest location:
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i(TAG, "Location " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Create instance for current user lat and lng
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add user position marker
currentUserPositionMarker(latLng);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
}
};
/**
* Add Marker for user current position
*
* #param latLng current lat and lng of user
*/
private void currentUserPositionMarker(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(CURRENT_POSITION);
mCurrLocationMarker = gMap.addMarker(markerOptions);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
#Override
public void onPause() {
super.onPause();
if (mFusedLocationProviderClient != null) {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.getUiSettings().setMapToolbarEnabled(false);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES); // 3 seconds interval
mLocationRequest.setFastestInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (isFineLocationPermissionGranted())
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
You need to get the last known location of the device, use this link to get the last known location, and then display the marker where you want.
This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 5 years ago.
I am new with maps in android i have this code :
enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent intent1 = getIntent();
lat = intent1.getStringArrayExtra("latitute");
lon = intent1.getStringArrayExtra("longitude");
id = intent1.getStringArrayExtra("id");
emails = intent1.getStringArrayExtra("emails");
latitude=intent1.getDoubleExtra("MyLat",0);
lonitude=intent1.getDoubleExtra("MyLon",0);
req_button =(Button)findViewById(R.id.R_id);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,5000);
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Search_for_Accepted_Job();
Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng [] sydeny = new LatLng[lat.length];
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// Add a marker in Sydney and move the camera
for (int i=0 ; i< lat.length;i++) {
sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));
}
for (int i=0 ; i< sydeny.length;i++) {
mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
}
LatLng sydeny1 = new LatLng(latitude,lonitude);
mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
public void Request(View view) {
Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
for (int i=0; i< lat.length;i++)
{
send_request(id[i]);
}
req_button.setEnabled(false);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
lonitude=location.getLatitude();
lonitude=location.getLongitude();
}
So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
(GoogleMap.OnMyLocationButtonClickListener
GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .
To correctly use location in your app, you need to handle asking user permission to turn on location in settings (in case it is turned off) and then follow the steps in the documentation:
https://developer.android.com/training/location/retrieve-current.html
To answer your question exactly, did you try location.getLatitude() and location.getLongitude()?
I'm trying to get the coordinates but without success. The result is 0 . But when I write:
googleMap.setMyLocationEnabled(true);
I can see the blue dot. I'm trying to get these values with this code:
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
After that, lat and lng are 0.
My whole code:
public class GPS_maps extends Activity {
// Google Map
private GoogleMap googleMap;
static Location currentLocation;
static double lat , lng;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
coordinates = (TextView) findViewById(R.id.txt_coordinates);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// googleMap.setMyLocationEnabled(true);
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng));
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
googleMap.animateCamera(yourLocation);
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}}
}
I don't get any errors. Where is my mistake?
Try the following:
Remove static modifier from the declaration of lat, lan.
Make sure you are sending in the correct syntax to setCoordiante.
To make sure the lat and lan are right, print them out right after you get them.
I'm developing an app that uses the Google Maps V2 API and I'm having trouble do get my coordinates and to put it into the LatLng object... Here's my code:
public class TelaMapa extends android.support.v4.app.FragmentActivity
implements OnMapClickListener, OnCameraChangeListener{
// Google Map
protected GoogleMap googleMap;
private SupportMapFragment mapFragment;
protected AndroidLocationSource locationSource;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_mapa);
}
#Override
protected void onResume(){
super.onResume();
configureMap();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void configureMap() {
if (googleMap == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager LM = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String bestProvider = LM.getBestProvider(new Criteria(),true);
Location localAtu;
/*Location myLocation = LM.getLastKnownLocation(bestProvider);
double lat= myLocation.getLatitude();
double lng = myLocation.getLongitude();
LatLng latLng = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));*/
if(bestProvider != null){
localAtu = LM.getLastKnownLocation(bestProvider);
} else {
localAtu = LM.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
LatLng latLng;
if(localAtu != null){
latLng = new LatLng(localAtu.getLatitude(), localAtu.getLongitude());
final CameraPosition position = new CameraPosition.Builder()
.target(latLng)
.bearing(0)
.tilt(0)
.zoom(17)
.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
googleMap.moveCamera(update);
adicionarMarcador(googleMap, latLng);
locationSource = new AndroidLocationSource();
googleMap.setLocationSource(locationSource);
locationSource.setLocation(latLng);
} else {
Toast.makeText(getApplicationContext(),
"GPS desligado ou indisponível!", Toast.LENGTH_LONG)
.show();
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Desculpe! Não foi possível criar o mapa!", Toast.LENGTH_SHORT)
.show();
}
}
}
That's it, I installed it in my Motorola Atrix and it always show me the toast in the else
block... Thanks for reading!
Answered by Sanket Kachhela!
Just use this tutorial and it will work fine!
androidhive.info/2012/07/android-gps-location-manager-tutorial
I've been following a series of tutorials to make a basic restaurant locator app for android using Google places with maps API v2. The problem I am having, is that my gps location is correct, but the marker drawn on the map to show the users location is approximately 60-65 miles south east of the users actual location.
Here is the code for my Location class:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
and finally here is the code for my map activity:
public class PlacesMapActivity extends FragmentActivity {
double latitude;
double longitude;
LatLng USER=null;
LatLng LOCATION=null;
PlacesList nearPlaces;
private GoogleMap map;
private int userIcon, locationIcon;
String address;
String name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
userIcon = R.drawable.mark_red;
locationIcon = R.drawable.mark_blue;
Intent i = getIntent();
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
String user_location = (user_latitude + ", " + user_longitude);
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView);
map = fm.getMap();
USER = new LatLng((int) (Double.parseDouble(user_latitude)),
(int) (Double.parseDouble(user_longitude)));
Marker user = map.addMarker(new MarkerOptions().position(USER)
.title("This is you.")
.snippet(user_location)
.icon(BitmapDescriptorFactory
.fromResource(userIcon)));
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
if(nearPlaces != null) {
for(Place place : nearPlaces.results) {
latitude = place.geometry.location.lat;
longitude = place.geometry.location.lng;
name = place.name;
address= place.vicinity;
}
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for(int c = 0; c < nearPlaces.results.size(); c++){
final LatLng pos = new LatLng(nearPlaces.results.get(c).geometry.location.lat,
nearPlaces.results.get(c).geometry.location.lng);
builder.include(pos);
map.addMarker(new MarkerOptions().position(pos)
.title(nearPlaces.results.get(c).name)
.snippet(nearPlaces.results.get(c).vicinity)
.icon(BitmapDescriptorFactory
.fromResource(locationIcon)));
}
}
map.moveCamera(CameraUpdateFactory.newLatLngZoom(USER, 14));
map.animateCamera(CameraUpdateFactory.zoomTo(9), 2000, null);
}
I tried to attach a screenshot, apparently I can't yet. I set the marker snippet to show the users latitude and longitude when clicked. When I click the users marker it shows the correct longitude and latitude (checked them on the internet, its within a block of my actual location), but as I stated the marker for the user always shows 60-65 miles south east. Also, the locations of the Places results are all correct and the markers in the correct locations.
any help is greatly appreciated. Cheers.
In your code below
USER = new LatLng((int) (Double.parseDouble(user_latitude)),
(int) (Double.parseDouble(user_longitude)));
Don't convert latitude-longitude to int, instead keep them as double.
Cheers !