How to get current latitude and longitude in android example

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

Check out 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

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

Network Location Provider vs GPS Location Provider

  • The network Location provider is comparatively faster than the GPS provider in providing the location coordinates.
  • GPS providers may be very very slow in indoor locations and will drain the mobile battery.
  • The network location provider depends on the cell tower and returns to 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 a 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 the network location providers for our Android app.

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

Create LocationManager Instance

For any background Android Service, we need to get a reference for using it. Similarly, location service references 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 is 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 of seconds.

Also, LocationListener has 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 user disables the provider.

onProviderEnabled(String provider) — Called when the user enables the provider.

onStatusChanged(String provider, int status, Bundle extras) — This callback will never be invoked onAndroid Q and above, and providers can be considered as always in theLocationProvider#AVAILABLEstate.

Let’s see the example for getting the current location in android.

Get the current location in the android example

Using Location Listener

I have created a service that extends locationListener. By extending 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 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 a 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 providers available to get the location.

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

Using Network Provider to get location

Once we know that the network provider is enabled, Then, you can request the location update from locationLintener usingLocationManager.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 the above you can see that, we can also get the last known location from the location manager usingNETWORK_PROVIDER.

Using a GPS provider to get the location

Same as the 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 the last known location from the location manager using GPS_PROVIDER.

All your location updates are received in LocationListener callbacks.

Stop receiving location

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

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

The entire Android app code is as follows,

GpsTracker.java

class GpsTracker extends Service implements LocationListener {
        private final Context mContext;

        // flag for GPS status
        boolean isGPSEnabled = false;

        // flag for network status
        boolean isNetworkEnabled = false;

        // flag for GPS status
        boolean canGetLocation = false;

        Location location; // location
        double latitude; // latitude
        double longitude; // longitude

        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

        // Declaring a Location Manager
        protected LocationManager locationManager;

        public GpsTracker(Context context) {
            this.mContext = context;
            getLocation();
        }

        public Location getLocation() {
            try {
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

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

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

                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    // First get location from 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();
                            }
                        }
                    }

                    // if GPS Enabled get lat/long using GPS Services
                    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();
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return location;
        }

        /**
         * Stop using GPS listener
         * Calling this function will stop using GPS in your app
         * */

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

        /**
         * Function to get latitude
         * */

        public double getLatitude(){
            if(location != null){
                latitude = location.getLatitude();
            }

            // return latitude
            return latitude;
        }

        /**
         * Function to get longitude
         * */

        public double getLongitude(){
            if(location != null){
                longitude = location.getLongitude();
            }

            // return longitude
            return longitude;
        }

        /**
         * Function to check GPS/wifi enabled
         * @return boolean
         * */

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        /**
         * Function to show settings alert dialog
         * On pressing Settings button will lauch Settings Options
         * */

        public void showSettingsAlert(){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            // Setting Dialog Title
            alertDialog.setTitle("GPS is settings");

            // Setting Dialog Message
            alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

            // On pressing Settings button
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            // on pressing cancel button
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alertDialog.show();
        }

        @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) {
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    }

MainActivity.java

public class MainActivity extends AppCompatActivity {

        private GpsTracker gpsTracker;
        private TextView tvLatitude,tvLongitude;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            tvLatitude = (TextView)findViewById(R.id.latitude);
            tvLongitude = (TextView)findViewById(R.id.longitude);

            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();
            }
        }

        public void getLocation(View view){
            gpsTracker = new GpsTracker(MainActivity.this);
            if(gpsTracker.canGetLocation()){
                double latitude = gpsTracker.getLatitude();
                double longitude = gpsTracker.getLongitude();
                tvLatitude.setText(String.valueOf(latitude));
                tvLongitude.setText(String.valueOf(longitude));
            }else{
                gpsTracker.showSettingsAlert();
            }
        }
    }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.velmurugan.getcurrentlatitudeandlongitudeandroid">

        <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"/>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

Android Output

display location on emulator

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. ClickMore Button from your emulator’s layout.
More option button on emulator
  1. Select Location Then set the Latitude and Longitude values. Then pressSendto set the Latitude and Longitude values to the emulator device.
Set location on emulator

You can download this example in GITHUB.

Conclusion

Thank you for the reading. I hope, Now you can get the current latitude and longitude on your android device. If you have any issues please put them in the comments section.


Comments

One response to “How to get current latitude and longitude in android example”

  1. […] How To Get Current Latitude And Longitude In Android […]

Leave a Reply

Your email address will not be published. Required fields are marked *


Latest Posts