I am trying to create an app that will get the current location of the phone and display it as a marker on the map. I am using devices with different types of android versions. It worked fine in Lollipop and displayed my current location but it's not working on the other versions, it only displays the map. It doesn't provide me an error message so I'm not really sure what is happening.
This is the code that I used to get the current location:
public void getLocation() {
try {
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = _locationManager.isProviderEnabled(_locationManager.GPS_PROVIDER);
isNetworkEnabled = _locationManager.isProviderEnabled(_locationManager.NETWORK_PROVIDER);
if (_locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (_locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
// Ask for update
Location mobileLocation = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
onLocationChanged(mobileLocation);
}
Location netLocation = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null) {
onLocationChanged(netLocation);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location userLocation) {
if (userLocation == null) {
Log.e(TAG, "NO Internet");
return;
}
_longitude = userLocation.getLongitude();
_latitude = userLocation.getLatitude();
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(_latitude, _longitude)).title("I'm Here"));
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(userLocation.getLatitude(), userLocation.getLongitude(), 1);
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String fullLocation = "Longitude : " + userLocation.getLongitude() + "\nLatitude : " + userLocation.getLatitude() + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + fullLocation);
}
Thank you!