How to get Latitude and Longitude of the mobile device in android?

Viewed 335535

How do I get the current Latitude and Longitude of the mobile device in android using location tools?

8 Answers

Use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

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

You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

Best way is

Add permission manifest file

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

Then you can get GPS location or if GPS location is not available then this function return NETWORK location

    public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
    LocationManager lm = (LocationManager)
            mContext.getSystemService(Context.LOCATION_SERVICE);
    assert lm != null;
    isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    Location networkLoacation = null, gpsLocation = null, finalLoc = null;
    if (isGpsEnabled)
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return null;
        }gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (isNetworkLocationEnabled)
        networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    if (gpsLocation != null && networkLoacation != null) {

        //smaller the number more accurate result will
        if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
            return finalLoc = networkLoacation;
        else
            return finalLoc = gpsLocation;

    } else {

        if (gpsLocation != null) {
            return finalLoc = gpsLocation;
        } else if (networkLoacation != null) {
            return finalLoc = networkLoacation;
        }
    }
    return finalLoc;
}

You can use FusedLocationProvider

For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   ...
   ...
   ...
   implementation 'com.google.android.gms:play-services-location:17.0.0'
}

Permissions in Manifest

Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

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

As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.

ActivityCompat.requestPermissions(
    this,
    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
    PERMISSION_ID
)

Then you can use the FusedLocationProvider Client to get the updated location in your desired place.

    mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
        var location: Location? = task.result
        if (location == null) {
            requestNewLocationData()
        } else {
            findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
            findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
        }
    }

You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:

private fun requestNewLocationData() {
    var mLocationRequest = LocationRequest()
    mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    mLocationRequest.interval = 0
    mLocationRequest.fastestInterval = 0
    mLocationRequest.numUpdates = 1

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    mFusedLocationClient!!.requestLocationUpdates(
            mLocationRequest, mLocationCallback,
            Looper.myLooper()
    )
}

Plug and play location-manager that can be used both in XML-based projects and Jetpack Compose projects (personally using it in JetpackCompose)

class LocationManager(context: Context): LocationCallback() {

val context = context
var publicCompletion: ((Double, Double) -> Unit)? = null

var fusedLocationProviderClient = FusedLocationProviderClient(
    context
)

fun requestLocationPermission() {
    val activity = context as Activity?
    ActivityCompat.requestPermissions(
        activity!!,
        arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION
        ),
        101
    )
}

fun checkIfLocationPermissionIsGranted(): Boolean {
    return (ActivityCompat.checkSelfPermission(
        context,
        Manifest.permission.ACCESS_FINE_LOCATION
    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
        context,
        Manifest.permission.ACCESS_COARSE_LOCATION
    ) != PackageManager.PERMISSION_GRANTED
            )
}

fun getLatitudeLongitude(completion: (Double, Double) -> Unit) {
    publicCompletion = { latitude, longitude ->
        completion(latitude, longitude)
    }

    if (ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        val activity = context as Activity?
        fusedLocationProviderClient.lastLocation.addOnCompleteListener(activity!!) { task ->
            var location: Location? = task.result
            if (location != null) {
                publicCompletion?.let { it(location!!.latitude, location!!.longitude) }
            } else {
                requestLocationUpdates()
            }
        }
    }
}

fun requestLocationUpdates() {
    var request = LocationRequest()
    request.priority = com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY
    request.fastestInterval = 0
    request.numUpdates = 1

    if (ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        fusedLocationProviderClient.requestLocationUpdates(
            request, this, Looper.myLooper()
        )
    }
}

override fun onLocationResult(p0: LocationResult?) {
    super.onLocationResult(p0)

    publicCompletion?.let { it(p0!!.lastLocation!!.latitude, p0!!.lastLocation!!.longitude) }
}

override fun onLocationAvailability(p0: LocationAvailability?) {
    super.onLocationAvailability(p0)
}
}
Related