In 2019 Best Offical Solution in Kotlin

Google API Client/FusedLocationApi are deprecated and Location Manager is not useful at all. So Google prefer Fused Location Provider Using the Google Play services location APIs "FusedLocationProviderClient" is used to get location and its better way for battery saving and accuracy

Here is sample code in kotlin to get the last known location /one-time location( equivalent to the current location)

 // declare a global variable of FusedLocationProviderClient
    private lateinit var fusedLocationClient: FusedLocationProviderClient

// in onCreate() initialize FusedLocationProviderClient
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

 /**
     * call this method for receive location
     * get location and give callback when successfully retrieve
     * function itself check location permission before access related methods
     *
     */
    fun getLastKnownLocation() {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location->
                    if (location != null) {
                       // use your location object
                        // get latitude , longitude and other info from this
                    }

                }

    }

If your app can continuously track the location then you have to receive Receive location updates

Check the sample for that in kotlin

// declare a global variable FusedLocationProviderClient
        private lateinit var fusedLocationClient: FusedLocationProviderClient

    // in onCreate() initialize FusedLocationProviderClient
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)


      // globally declare LocationRequest
        private lateinit var locationRequest: LocationRequest

        // globally declare LocationCallback    
        private lateinit var locationCallback: LocationCallback


        /**
         * call this method in onCreate
         * onLocationResult call when location is changed 
         */
        private fun getLocationUpdates()
        {

                fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
                locationRequest = LocationRequest()
                locationRequest.interval = 50000
                locationRequest.fastestInterval = 50000
                locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
                locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
                locationCallback = object : LocationCallback() {
                    override fun onLocationResult(locationResult: LocationResult?) {
                        locationResult ?: return

                        if (locationResult.locations.isNotEmpty()) {
                            // get latest location 
                            val location =
                                locationResult.lastLocation
                            // use your location object
                            // get latitude , longitude and other info from this
                        }


                    }
                }
        }

        //start location updates
        private fun startLocationUpdates() {
            fusedLocationClient.requestLocationUpdates(
                locationRequest,
                locationCallback,
                null /* Looper */
            )
        }

        // stop location updates
        private fun stopLocationUpdates() {
            fusedLocationClient.removeLocationUpdates(locationCallback)
        }

        // stop receiving location update when activity not visible/foreground
        override fun onPause() {
            super.onPause()
            stopLocationUpdates()
        }

        // start receiving location update when activity  visible/foreground
        override fun onResume() {
            super.onResume()
            startLocationUpdates()
        }

Make sure you take care about Mainfaist permission and runtime permission for location

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

and for Gradle add this

implementation 'com.google.android.gms:play-services-location:17.0.0'

For more details follow these official documents

https://developer.android.com/training/location/retrieve-current

https://developer.android.com/training/location/receive-location-updates

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

Answer from Mayank Sharma on Stack Overflow
Top answer
1 of 8
56

In 2019 Best Offical Solution in Kotlin

Google API Client/FusedLocationApi are deprecated and Location Manager is not useful at all. So Google prefer Fused Location Provider Using the Google Play services location APIs "FusedLocationProviderClient" is used to get location and its better way for battery saving and accuracy

Here is sample code in kotlin to get the last known location /one-time location( equivalent to the current location)

 // declare a global variable of FusedLocationProviderClient
    private lateinit var fusedLocationClient: FusedLocationProviderClient

// in onCreate() initialize FusedLocationProviderClient
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

 /**
     * call this method for receive location
     * get location and give callback when successfully retrieve
     * function itself check location permission before access related methods
     *
     */
    fun getLastKnownLocation() {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location->
                    if (location != null) {
                       // use your location object
                        // get latitude , longitude and other info from this
                    }

                }

    }

If your app can continuously track the location then you have to receive Receive location updates

Check the sample for that in kotlin

// declare a global variable FusedLocationProviderClient
        private lateinit var fusedLocationClient: FusedLocationProviderClient

    // in onCreate() initialize FusedLocationProviderClient
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)


      // globally declare LocationRequest
        private lateinit var locationRequest: LocationRequest

        // globally declare LocationCallback    
        private lateinit var locationCallback: LocationCallback


        /**
         * call this method in onCreate
         * onLocationResult call when location is changed 
         */
        private fun getLocationUpdates()
        {

                fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
                locationRequest = LocationRequest()
                locationRequest.interval = 50000
                locationRequest.fastestInterval = 50000
                locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
                locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
                locationCallback = object : LocationCallback() {
                    override fun onLocationResult(locationResult: LocationResult?) {
                        locationResult ?: return

                        if (locationResult.locations.isNotEmpty()) {
                            // get latest location 
                            val location =
                                locationResult.lastLocation
                            // use your location object
                            // get latitude , longitude and other info from this
                        }


                    }
                }
        }

        //start location updates
        private fun startLocationUpdates() {
            fusedLocationClient.requestLocationUpdates(
                locationRequest,
                locationCallback,
                null /* Looper */
            )
        }

        // stop location updates
        private fun stopLocationUpdates() {
            fusedLocationClient.removeLocationUpdates(locationCallback)
        }

        // stop receiving location update when activity not visible/foreground
        override fun onPause() {
            super.onPause()
            stopLocationUpdates()
        }

        // start receiving location update when activity  visible/foreground
        override fun onResume() {
            super.onResume()
            startLocationUpdates()
        }

Make sure you take care about Mainfaist permission and runtime permission for location

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

and for Gradle add this

implementation 'com.google.android.gms:play-services-location:17.0.0'

For more details follow these official documents

https://developer.android.com/training/location/retrieve-current

https://developer.android.com/training/location/receive-location-updates

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

2 of 8
32

When GetUserLocation returns, locationManager goes out of scope and presumably is destroyed, preventing onLocationChanged from being called and providing updates.

Also, you've defined mylocation inside of GetUserLocation so it also goes out of scope and further kills any chance or your getting an update.

You have not shown where and how the outer mylocation is declared (outside of GetUserLocation), but how ever it is declared, it is being shadowed by the one inside of GetUserLocation. So you aren't getting much.

Here is an example of how you might do it. (The variable thetext is defined within the layout xml and accessed with Kotlin extensions.)

// in the android manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// allow these through Appliation Manager if necessary

// inside a basic activity
private var locationManager : LocationManager? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    // Create persistent LocationManager reference
    locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?

    fab.setOnClickListener { view ->
        try {
            // Request location updates
            locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
        } catch(ex: SecurityException) {
            Log.d("myTag", "Security Exception, no location available")
        }
    }
}

//define the listener
private val locationListener: LocationListener = object : LocationListener {
    override fun onLocationChanged(location: Location) {
        thetext.text = ("" + location.longitude + ":" + location.latitude)
    }
    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onProviderDisabled(provider: String) {}
}
🌐
Google
codelabs.developers.google.com › codelabs › while-in-use-location
Receive location updates in Android with Kotlin | Google Codelabs
March 27, 2026 - Add support to the app for Android 10 and 11 by adding logic to access location in the foreground location or while in use. ... To get you started as quickly as possible, you can build on this starter project.
Top answer
1 of 3
1

So here's how you can get your current location. I am skipping the permission part as you can do that yourself.

private fun isLocationEnabled(): Boolean {
        val locationManager: LocationManager =
            getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER
        )
    }
 private fun getLastLocation() {
        if (isLocationEnabled()) {
           fusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                val location: Location? = task.result
                if (location != null) {
                    //use the location latitude and logitude as per your use.
                    val latitude = location.latitude
                    val longitude = location.longitude
                }
            }
        }
2 of 3
0

you need to request location updates try the following for instance


    val fusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(activity)
    val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val location = locationResult.lastLocation
            if (location != null) {
                val latitude = location.latitude
                val longitude = location.longitude

                // Use latitude and longitude for your purposes
                Log.d("Location", "Latitude: $latitude, Longitude: $longitude")

                // Remove location updates after receiving one
                fusedLocationProviderClient.removeLocationUpdates(this)
            } else {
                Log.w("Location", "Failed to get location update")
            }
        }
    }

    if (ContextCompat.checkSelfPermission(
            activity,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // Request permissions if not granted
        val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
        activity.requestPermissions(permissions, LOCATION_PERMISSION_CODE)
        return
    }

    val locationRequest =
        LocationRequest.Builder(0L).setPriority(Priority.PRIORITY_HIGH_ACCURACY).build()

    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null)
🌐
Medium
medium.com › @kadampritesh46 › getting-user-location-and-converting-to-readable-address-in-android-using-kotlin-c1e585f59351
Getting User Location and Converting to Readable Address in Android using Kotlin | by Pritesh kadam | Medium
August 21, 2023 - -> if (location != null) { val geocoder = Geocoder(this, Locale.getDefault()) val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1) if (addresses.isNotEmpty()) { val address = addresses[0] val addressLine = address.getAddressLine(0) // Now you possess the human-readable address in 'addressLine' } } } .addOnFailureListener { exception: Exception -> // Handle errors that arise during location retrieval here } In this guide, we’ve grasped using Kotlin and Android Location APIs to get live user locations and convert them to readable addresses.
🌐
Techpass Master
techpassmaster.com › learn, practice, implement › get current location in android studio using kotlin
Get Current Location in Android Studio using Kotlin - Techpass Master
January 13, 2025 - First, you have to need to create a project to get your current location, below are the steps you can follow step by step. Start a new Android Studio Project. Select Empty Activity and click Next. Project Name: RealTimeLocation. Choose Language: Kotlin.
🌐
Medium
medium.com › @manuaravindpta › getting-current-location-in-kotlin-30b437891781
Getting Current Location in Kotlin | by Manu Aravind | Medium
January 28, 2022 - With respect to fused location provider, we can broadly classify the API usage in three use cases. getLastLocation(GoogleApiClient) this API should be used when there is no need for continuous access to location from an application. Like one shot access or get user location based on some action.
🌐
Android Hire
androidhire.com › home › getting current location in android using kotlin
Getting Current Location In Android Using Kotlin - Android Hire
June 14, 2020 - Also this method will check first if our permission is granted or not and if the location setting is turned on. @SuppressLint("MissingPermission") private fun getLastLocation() { if (checkPermissions()) { if (isLocationEnabled()) { mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task -> var location: Location?
Find elsewhere
🌐
Android Developers
developer.android.com › api reference › location
Location | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-the-current-gps-location-programmatically-on-android-using-kotlin
How to get the current GPS location programmatically on Android using Kotlin?
November 28, 2020 - import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity(), LocationListener { private lateinit var locationManager: LocationManager private lateinit var tvGpsLocat
🌐
en.proft.me
en.proft.me › 2019 › 01 › 3 › how-get-location-latitude-longitude-android-kotlin
How to get current location (latitude, longitude) in Android using Kotlin | en.proft.me
The Android OS itself contains a location framework with classes in the package android.location. However, the official position of Google is to favor the Google Play Services Location API because it is more elaborate and simpler to use. We follow this suggestion and talk about the services API in the following paragraphs.
🌐
Esri Developer
developers.arcgis.com › kotlin › device-location
Device location | ArcGIS Maps SDK for Kotlin | Esri Developer
You can display the current location of the device in a map view by using its location display (LocationDisplay). The map view location display handles getting the current location from the location data source and displaying it on top of the map.
🌐
Stack Overflow
stackoverflow.com › questions › 65812102 › kotlin-how-to-get-current-location
android - Kotlin: How to get current location? - Stack Overflow
In Kotlin, unlike Java, you need to specify whether a variable can be null or not. Accessing such a variable is done through the syntax variable?.method() to signify that you understand that the call may evaluate to null. ... Since locationManager was assigned a nullable type, it is now also nullable. You could mitigate this by doing something like: val locationManager = (context?.getSystemService(LOCATION_SERVICE) as?
🌐
Google
developers.google.com › google maps platform › android › maps sdk for android › select current place and show details on a map
Select Current Place and Show Details on a Map | Maps SDK for Android | Google for Developers
Upon selection, a marker is added to the map at the chosen location, displaying its name and address, and the map's camera focuses on that place. Code samples are provided in both Java and Kotlin, covering initialization, permission handling, location retrieval, place selection, and UI updates.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-current-location-in-android
How to Get Current Location in Android? - GeeksforGeeks
Many apps in Android uses user's locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user's latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query: 6 min read How to Get Current Time and Date in Android?
Published   April 7, 2025
🌐
GitHub
github.com › botradingblog1 › android-kotlin-geo-location-1
GitHub - botradingblog1/android-kotlin-geo-location-1: Sample program on how to get the device's geo location on Android using Kotlin.
Sample program on how to get the device's geo location on Android using Kotlin. - botradingblog1/android-kotlin-geo-location-1
Starred by 3 users
Forked by 3 users
Languages   Kotlin 100.0% | Kotlin 100.0%
Top answer
1 of 1
6

Try this code for getting the current location:

File activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

    <TextView
            android:id="@+id/latTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Latitude: "/>

    <TextView
            android:id="@+id/lonTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Longitude: "/>

</LinearLayout>

File MainActivity.kt

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*

class MainActivity : AppCompatActivity() {

    val PERMISSION_ID = 42
    lateinit var mFusedLocationClient: FusedLocationProviderClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        getLastLocation()
    }

    @SuppressLint("MissingPermission")
    private fun getLastLocation() {
        if (checkPermissions()) {
            if (isLocationEnabled()) {

                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()
                    }
                }
            } else {
                Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivity(intent)
            }
        } else {
            requestPermissions()
        }
    }

    @SuppressLint("MissingPermission")
    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()
        )
    }

    private val mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            var mLastLocation: Location = locationResult.lastLocation
            findViewById<TextView>(R.id.latTextView).text = mLastLocation.latitude.toString()
            findViewById<TextView>(R.id.lonTextView).text = mLastLocation.longitude.toString()
        }
    }

    private fun isLocationEnabled(): Boolean {
        var locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER
        )
    }

    private fun checkPermissions(): Boolean {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            return true
        }
        return false
    }

    private fun requestPermissions() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSION_ID
        )
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == PERMISSION_ID) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                getLastLocation()
            }
        }
    }
}

See here for more details: Getting Current Location (latitude, longitude) in Android using Kotlin

🌐
GeeksforGeeks
geeksforgeeks.org › kotlin › using-fused-location-api-to-fetch-current-location-in-android
Using Fused Location API to Fetch Current Location in Android - GeeksforGeeks
July 23, 2025 - Now if the permissions for location are granted then we will continue with our work, if not then we will gather it call the setLocationListner() function, which is responsible for getting the current location.
🌐
TutorialsPoint
tutorialspoint.com › the-simplest-way-to-get-the-user-s-current-location-on-android-using-kotlin
The simplest way to get the user&#039;s current location on Android
November 28, 2020 - addresses = null; try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } catch (Exception ioException) { Log.e("", "Error in getting address for the location"); } if (addresses == null || addresses.size() == 0) { msg = "No address found for the location"; sendResultsToReceiver(1, msg); } else { Address address = addresses.get(0); String addressDetails = address.getFeatureName() + " " + address.getThoroughfare() + " " + "Locality: " + address.getLocality() + " " + "County: " + address.getSubAdminArea() + " " + "State: " + address.getAdminArea() + " " +
🌐
Android Developers
developer.android.com › core areas › sensors and location › get the last known location
Get the last known location | Sensors and location | Android Developers
June 2, 2023 - Once you have created the Location Services client you can get the last known location of a user's device. When your app is connected to these you can use the fused location provider's getLastLocation() method to retrieve the device location.