Get Current Location in Android (Kotlin) and Show It on a Map

Updated:

This guide shows how to get the user’s current location in Android with Kotlin and show it on a Google Map. It uses the Fused Location Provider (the recommended API), the modern permission request flow, and Jetpack Compose – with notes for XML/View apps.

📘 New to Kotlin? Learn it step by step with our free Kotlin course: 51 short lessons with runnable examples, from your first program to coroutines.

Get current location in Android using Kotlin
Get Current Location in Android Studio using Kotlin (Thumbnail)

Updated for 2026: the old approach (requestPermissions() + lastLocation) often returns null and asks only for fine location. On Android 12+, you must declare and request both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION – otherwise the request is ignored (Android Developers).

Step 1: Add the dependencies

dependencies {
    // Fused Location Provider
    implementation("com.google.android.gms:play-services-location:21.3.0")
    // await() for Play services Tasks
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2")
    // Google Maps for Compose (pulls in the Maps SDK) – only if you show a map
    implementation("com.google.maps.android:maps-compose:6.2.1") // check for newer
}

Step 2: Declare the permissions

In AndroidManifest.xml:

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

Only add ACCESS_BACKGROUND_LOCATION if you truly need location while the app is closed – it needs a separate request and extra Play Store review.

Step 3: Ask for permission at runtime

Request both permissions together. The user may choose “Approximate”, so your app should still work with coarse location.

@Composable
fun rememberLocationPermission(onResult: (granted: Boolean) -> Unit) =
    rememberLauncherForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { result ->
        val granted = result[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
                      result[Manifest.permission.ACCESS_COARSE_LOCATION] == true
        onResult(granted)
    }

// Usage:
val launcher = rememberLocationPermission { granted -> if (granted) loadLocation() }
Button(onClick = {
    launcher.launch(arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION
    ))
}) { Text("Use my location") }

In an Activity or Fragment (XML views), use registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) the same way.

Step 4: Get the current location

getCurrentLocation() asks for a fresh fix instead of returning a possibly-stale or empty cached one like lastLocation. Wrap it in a small helper:

class LocationHelper(context: Context) {
    private val client = LocationServices.getFusedLocationProviderClient(context)

    @SuppressLint("MissingPermission") // call only after permission is granted
    suspend fun currentLocation(): Location? {
        val request = CurrentLocationRequest.Builder()
            .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
            .setMaxUpdateAgeMillis(30_000) // accept a fix up to 30 s old
            .build()
        return client.getCurrentLocation(request, CancellationTokenSource().token).await()
    }
}

It returns null if location is switched off on the device – see the problems table below.

Step 5: Show the location on a map (Compose)

You need a Maps API key from the Google Cloud console with “Maps SDK for Android” enabled. Add it to the manifest inside <application> (keep the key out of Git with the Secrets Gradle Plugin):

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}" />
@Composable
fun MyLocationMap(helper: LocationHelper) {
    val scope = rememberCoroutineScope()
    var position by remember { mutableStateOf<LatLng?>(null) }
    val camera = rememberCameraPositionState()

    val launcher = rememberLocationPermission { granted ->
        if (granted) scope.launch {
            helper.currentLocation()?.let { loc ->
                val latLng = LatLng(loc.latitude, loc.longitude)
                position = latLng
                camera.animate(CameraUpdateFactory.newLatLngZoom(latLng, 16f))
            }
        }
    }
    LaunchedEffect(Unit) {
        launcher.launch(arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ))
    }

    GoogleMap(
        modifier = Modifier.fillMaxSize(),
        cameraPositionState = camera,
        properties = MapProperties(isMyLocationEnabled = position != null)
    ) {
        position?.let { Marker(state = MarkerState(it), title = "You are here") }
    }
}

isMyLocationEnabled draws the blue “my location” dot and button; only turn it on after permission is granted.

Current latitude and longitude shown in the app
Get Current Location in Android Studio using Kotlin (final App result

Optional: live location updates

@SuppressLint("MissingPermission")
fun FusedLocationProviderClient.locationFlow(): Flow<Location> = callbackFlow {
    val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5_000).build()
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            result.lastLocation?.let { trySend(it) }
        }
    }
    requestLocationUpdates(request, callback, Looper.getMainLooper())
    awaitClose { removeLocationUpdates(callback) }
}

Collect it while the screen is visible (for example with collectAsStateWithLifecycle) and stop when you no longer need it – continuous GPS drains the battery.

Common problems

ProblemFix
Location is always nullLocation is turned off, or the emulator has no location. Turn on Location in quick settings; on the emulator set one in Extended controls › Location.
Permission dialog never appearsDeclare both FINE and COARSE in the manifest and request both together.
Map is blank / greyAPI key missing or wrong, or “Maps SDK for Android” not enabled for that key; check Logcat for an authorization error.
Only approximate locationThe user picked “Approximate”. Explain why you need precise location and request again, or work with coarse accuracy.
SecurityExceptionYou called the location API before permission was granted.

FAQ

What is the best way to get location in Android?

Use the Fused Location Provider from Google Play services: getCurrentLocation() for a one-time fix and requestLocationUpdates() for continuous tracking.

Is lastLocation deprecated?

No, but it returns the last cached fix, which can be old or null. For “where am I now?”, getCurrentLocation() is the better choice.

Do I need an API key to get the location?

No. Only showing Google Maps needs a Maps API key. Getting latitude and longitude with the Fused Location Provider does not.

More Android guides

6 Comments

  1. Léo

    Não vejo o github dele para saber se o código está todo depreciado ou em partes. Não gosto de ler tanto assim, toda a explicação fragmentada, esse tipo de explicação afastas novos usuários de seu contato pessoal, não gosta de dinheiro?

  2. marc

    I installed the app and it seems to work but the location never changes. on google maps i can see the location changing but in this app it is stuck at the first place when i first hit the get location button. Any thoughts as to what might be wrong?

    1. Sardar khan

      Hi mark Fused Provider Last Location some times return null if you are trying first time or location is fetched first time.

Comments are closed.

WhatsApp us📞 Call now