How to get current latitude and longitude in android[Download]

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.

I have added coding for getting the current location in the device using Location Manager.

There are two 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

  1. Provide permissions for the manifest file for receiving the location update.
  2. Create LocationManager instance as a reference to the location service.
  3. Request location from LocationManager.
  4. Receive location update from LocationListener on change of location.

Provide 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.


Related Post

Get current speed using GPS android

Google Places Autocomplete Android Example [Updated]


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.

Get location in Android Example

Current Location Finder This example provides current location update using the GPS provider. Entire Android app code is as follows,

GPSTracker.java

import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;

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 &amp;&amp; !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 &amp;&amp; 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 &amp;&amp; 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

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
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>

Android Output

Display latitude and longitude
Current Location Latitude and Longitude

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.
More Button on Emulator to set latitude and longitude
Android Emulator More Button

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

set current latitude and longitude in emulator
Set Latitude and Longitude For Android Emulator

Conclusion

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.

Thank you for the reading.

github_link

11 Responses

  1. hi i'm chandirasekar i need ur help for android app

    " how to find the tower name without any network connect (gps or wifi) using android …..it's possible or not

    if possible mean send that code to [email protected] please help me thank you?

  2. Hai, i need google map v2 showing map in android with latitude and longlitude .but i tried but it's not worked.please help me.

  3. its working in android devices, if you need to run in android emulator you have to made some config while creating the emulator
    public class MainActivity extends Activity {

    // Google Map
    private GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {

    initilizeMap();

    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    googleMap.setMyLocationEnabled(true);

    // Enable / Disable zooming controls
    googleMap.getUiSettings().setZoomControlsEnabled(false);

    // Enable / Disable my location button
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);

    // Enable / Disable Compass icon
    googleMap.getUiSettings().setCompassEnabled(true);

    // Enable / Disable Rotate gesture
    googleMap.getUiSettings().setRotateGesturesEnabled(true);

    // Enable / Disable zooming functionality
    googleMap.getUiSettings().setZoomGesturesEnabled(true);

    double latitude = 13.0839;
    double longitude = 80.2700;

    MarkerOptions marker = new MarkerOptions().position(
    new LatLng(latitude, longitude));

    googleMap.addMarker(marker);

    CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(new LatLng(latitude,
    longitude)).zoom(15).build();

    googleMap.animateCamera(CameraUpdateFactory
    .newCameraPosition(cameraPosition));

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

    }

    @Override
    protected void onResume() {
    super.onResume();
    initilizeMap();
    }

    /**
    * function to load map If map is not created it will create it for you
    * */
    private void initilizeMap() {
    if (googleMap == null) {
    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
    R.id.map)).getMap();

    // check if map is created successfully or not
    if (googleMap == null) {
    Toast.makeText(getApplicationContext(),
    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
    .show();
    }
    }
    }
    }

Comments are closed.

Back to Top