Get Address from current location Kotlin

694 views Asked by At

I get the current location like this:

val fusedLocationClient: FusedLocationProviderClient =
            LocationServices.getFusedLocationProviderClient(LocalContext.current)
fun getLastKnownLocation() {
            fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                    if (location != null) {
                        longitude.value = location.longitude
                        latitude.value = location.latitude
                    }
                }
        }

How I can get the Address from it?

Update I implemented like this:

fun getLastKnownLocation() {
            fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                    if (location != null) {
                        longitude.value = location.longitude
                        latitude.value = location.latitude

                        val geocoder = Geocoder(app)
                        if (Build.VERSION.SDK_INT >= 33) {
                            geocoder.getFromLocation(
                                location.latitude, location.longitude, 1
                            ) { addresses ->
                                address.value = addresses.first().toString()
                            }
                        } 
                        else {
                            try {
                                val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1
                                )?.firstOrNull()
                                address.value = addresses.toString()
                            } catch (Exp: Exception) {
                                address.value = "No Address found"
                                println("$Exp")
                            }
                        }
                    }
                }
        }

But got this exception: java.io.IOException: eccc: DEADLINE_EXCEEDED: deadline exceeded after 4.907678698s

1

There are 1 answers

4
ace1234 On
val geocoder = Geocoder(this, Locale.getDefault())
val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)

https://developer.android.com/reference/kotlin/android/location/Geocoder