getFromLocation unstable Kotlin

242 Views Asked by At

I want to get the street address from longitude and latitude. Currently I am using geocoder.getFromLocation(latitute,longitude,1)

        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().getAddressLine(0)
                        }
                    } else {
                        try {
                            val addresses = geocoder.getFromLocation(
                                location.latitude,
                                location.longitude,
                                1)?.firstOrNull()
                            address.value = addresses?.getAddressLine(0) ?: "No address found"
                        } catch (Exp: Exception) {
                            address.value = "No address found"
                        }
                    }
                }
            }
    }

But is unstable and does not work sometimes. Geocoder does not get always the address and it takes to long.

Any idea what else I can use or what I should change on the implementation? Have a nice day!

0

There are 0 best solutions below