I\'ve been getting current location with GoogleApiClient
up until now but I\'ve just noticed that it\'s much simpler to do it with LocationManager
Use the following method to get the Location
object:
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v(TAG, "isGPSEnabled =" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v(TAG, "isNetworkEnabled =" + isNetworkEnabled);
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled && location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
} catch (Exception e) {
Log.e(TAG, "Location Not Found");
}
return location;
}
For more information on the method getLastKnownLocation
, please refer to the docs.