'Android Google Map - How to access user's location if permissions are granted

I'm building a Jetpack Compose app that requires access to user's current location. Here's my code for now.

val userDefaultLocation = LatLng(0.0, 0.0) // Default location

val locationPermissionsState = rememberMultiplePermissionsState(
    listOf(
        android.Manifest.permission.ACCESS_COARSE_LOCATION,
        android.Manifest.permission.ACCESS_FINE_LOCATION,
    )
)

val cameraPositionState = rememberCameraPositionState {
    if (locationPermissionsState.allPermissionsGranted) {
        position = ???
    } else {
        position = CameraPosition.fromLatLngZoom(userDefaultLocation, 11f)
    }
}

I'm using the Accompanist api and I have the corresponding permissions added in the Manifest file. Now my question is, if allPermissionsGranted is true, how can I access the user's location as a LatLng object. Thanks!



Solution 1:[1]

I'm not sure if I understand your question correctly, but if you just want to get the last known user location you can use FusedLocationProviderClient

You can find the official documentation following the below link https://developer.android.com/training/location/retrieve-current#:~:text=The%20fused%20location%20provider%20is,device's%20use%20of%20battery%20power.

A simple implementation would look like this:

private lateinit var fusedLocationClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

    fusedLocationClient.lastLocation
        .addOnSuccessListener { location : Location? ->
            // Got last known location. In some rare situations this can be null.
        }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikhail