I need to get the Lat and the Long of the current location to draw a route, my code works on the emulator but when I debug on real device, it does not. This is how I get the current location:
private void gotoCurrentLocation(){
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,listener);
Location myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(myLocation==null) { MYPLACE = null; return;}
MYPLACE = new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(ll).title("You're here"));
}
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MYPLACE = new LatLng(location.getLatitude(),location.getLongitude());
}
This is the map on the GenyMotion virtual device. When I debug on the real device, the map also has the tiny blue point at the current location like on the virtual device but MYPLACE
is null and it could not place a marker at the current location. Is there something with the code? Could someone help me out please!!
This is on the real device:
This could happen because on some devices the GPS takes some time to initialize. If you request for your current location before the GPS gets initialized you'll surely get a null location value, since the GPS hasn't been initialized yet.
There are several ways of preventing this scenario. I would suggest you to use Play Services for location detection or you can simply use a library called ,
You can request the Reactive Location to get the last known location which will prevent from getting a null value,
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
@Override
public void call(Location location) {
doSthImportantWithObtainedLocation(location);
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments