ive been trying to center a map on the users location, but it keeps saying the latLng variable is null. I have read that that happens because i am using the getLastKnownLocation, but I cant find any other way to do it (I am new to programing). I am working with the google api on Jellybean. Here is the code that i am using.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Latitude y longitud
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude,longitude);
//Mover el mapa a la posicion actual del usuario
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
} else {
// Show rationale and request permission.
}
try out this
Implements interface
GoogleApiClient.ConnectionCallbacks
and override methods onConnected and onConnectionSuspended in onConnectedImplenment
LocationListener
interface and override method in thatCheck permission in "AndroidManifest.xml
Mainly We can get location via GPS Provider and NETWORK provider. If we get null location Via GPS provider, then change Provider to NETWORK.