Hi, Today I’ll explain how to obtain the latitude and the longitude of the current position in order to load the Google maps at the current position. Several providers are available with android which can be used to get current position updates. They are the GPS provider, Network provider and Mock provider. The GPS provider will give you a more accurate current position than the Network provider. Following steps will helpful for you to get the current position.
-
Add a new permission to the AndroidMainfest.xml .
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/>
-
To initiate the LocationManager class: call getSystemService() of the Activity class.
LocationManager locationManager = (LocationManager) getSystemService(Context. LOCATION_SERVICE);
-
To request for updates: call requestLocationUpdates(). locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_ TIME_ BETWEEN_ UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
-
To get the current position : call getLastKnownLocation()of LocationManagerLocation location = locationManager. getLastKnownLocation (LocationManager.GPS _PROVIDER);** If your device initially doesn’t have any last known locations this will give you a RuntimeException. So you’ll have to handle that scenario. 🙂
- LocationListener to listen for updates and status changes.
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {} // to get continues updates
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}