How to get current latitude and longitude in android example

This Android tutorial is to help learn How to get current latitude and longitude in the Android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve people’s daily problem. For developing the location-aware application in android, it needs location providers.

Checkout my other useful post:

Android Capture Image From Camera Programmatically

Google Places Autocomplete Android Example

Types of location providers:

GPS Location Provider

Network Location Provider

Anyone of the above providers is enough to get the current location of the user or user’s device. But, it is recommended to use both providers as they both have different advantages. Because GPS provider will take the time to get the location to the indoor area. And, the Network Location Provider will not get location when the network connectivity is poor.

Network Location Provider vs GPS Location Provider

  • Network Location provider is comparatively faster than the GPS provider in providing the location coordinates.
  • GPS provider may be very very slow in indoor locations and will drain the mobile battery.
  • Network location provider depends on the cell tower and will return our nearest tower location.
  • GPS location provider will give our location accurately.

Steps to get current latitude and longitude in Android

  • Location permissions for the manifest file for receiving the location update.
  • Create LocationManager instance as a reference to the location service.
  • Request location from LocationManager.
  • Receive location update from LocationListener on change of location.

Location Permissions

To access current location information through location providers, we need to set permissions with the android manifest file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

As higher versions of Android need in-app permission so we will request app permission this way,

try {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
} catch (Exception e){
e.printStackTrace();
}

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app.

But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of a network provider.

Create LocationManager Instance As The Reference To The Location Service

For any background Android Service, we need to get a reference for using it. Similarly, location service reference will be created using the getSystemService() method. This reference will be added to the newly created LocationManager instance as follows.

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Request Current Location From LocationManager

After creating the location service reference, location updates are requested using the requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance and the LocationListener object over which the location to be updated.

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

Receive Location Update From LocationListener

Receive location update from LocationListener on change of location LocationListener will be notified based on the distance interval specified or the number seconds.

Also, LocationListener having its own callbacks to provide locations based on location / provider changes.

public interface LocationListener {
void onLocationChanged(Location var1);

void onStatusChanged(String var1, int var2, Bundle var3);

void onProviderEnabled(String var1);

void onProviderDisabled(String var1);
}

onLocationChanged(Location location) — Called when the location has changed.

onProviderDisabled(String provider) — Called when the provider is disabled by the user.

onProviderEnabled(String provider) — Called when the provider is enabled by the user.

onStatusChanged(String provider, int status, Bundle extras) — This callback will never be invoked on Android Q and above, and providers can be considered as always in the LocationProvider#AVAILABLE state.

Lets see the example for getting current location in android.

Get current location in android example

Using Location Listener

I have created service that extends locationListener. By extends Location Listener you can receive location updates.

class GpsTracker extends Service implements LocationListener {

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Requesting Location Permission

To get the current latitude and longitude you need a location permission.

if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}

Getting NetworkingProvider / GpsProvider

To get the networking / Gps providers, first we need to get location manager.

locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

Once, we get the location manager then we can get the location providers.

// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

check any one of the location provider available to get the location.

if (isGPSEnabled && isNetworkEnabled) {
//network provider is enabled
}

Using Network Provider to get location

Once we know that network provider enabled, Then , you can request the location update from locationLintener using LocationManager.NETWORK_PROVIDER.

if (isNetworkEnabled) {
//check the network permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

In above you can see that, we can also get last known location from the location manager using NETWORK_PROVIDER.

Using GPS provider to get location

Same like Network provider, we can request the location update using LocationManager.GPS_PROVIDER .

if (isGPSEnabled) {
if (location == null) {
//check the network permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}

Also,we can also get last known location from the location manager using GPS_PROVIDER.

All your location updates received in LocationListener callbacks.

Stop receiving location

To stop receiving location updates in location manager by using removeUpdates.

if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}

Entire Android app code is as follows,

GpsTracker.java

MainActivity.java

MainActivity.java

AndroidManifest.xml

Android Output

Note: If you are running this Android app on the emulator, you need to send the latitude and longitude explicitly for the emulator.

To send the latitude and longitude from your emulator,

  1. Click More Button from your emulator’s layout.

2. Select Location > Then set the Latitude and Longitude values. Then press Send to set the Latitude and Longitude value to the emulator device.

You can download this example in GITHUB.

Conclusion

Thank you for the reading.

I hope, Now you can able to get current latitude and longitude in your android device. If you have any issue please put it on the comments session.

Originally published at velmm.com on August 13, 2013.

Lead Software Engineer @htcindia | @github contributor | Blog writer @howtodoandroid | Quick Learner