Malo
Malo

Reputation: 1576

android geocoder void getfromlocation how to get addresses?

i have geocoder class in my android activity which contains google map

i need to reverse the geocode using

getFromLocation(double latitude, double longitude, int maxResults, Geocoder.GeocodeListener listener)

this method has void declaration but must returns list of addresses, according to google they said to do the below

Provides an array of Addresses that attempt to describe the area immediately surrounding the given latitude and longitude. The returned addresses should be localized for the locale provided to this class's constructor.

how to do that to get list of addresses if this method is void type?

Upvotes: 5

Views: 5983

Answers (2)

AndroidRocks
AndroidRocks

Reputation: 332

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
suspend fun getCityStateName(location : Location?) : String? =
    suspendCancellableCoroutine<String?> { cancellableContinuation ->
        location?.let { loc ->
            Geocoder(context).getFromLocation(
                loc.latitude, loc.longitude, 1
            ) { list -> // Geocoder.GeocodeListener
                list.firstOrNull()?.let { address ->
                    cancellableContinuation.resumeWith(
                        Result.success(
                            "${address.locality} ${address.adminArea}"
                            )
                        )
                    }
            }
        }
    }

Upvotes: 2

wolfOnix
wolfOnix

Reputation: 103

(Kotlin)

The list of addresses will be available when implementing the abstract method onGeocode(). To access the list of addresses you should declare a variable with an implementation for the GeocodeListener instance:

val geocodeListener = @RequiresApi(33) object : Geocoder.GeocodeListener {
    override fun onGeocode(addresses: MutableList<Address>) {
        // do something with the addresses list
    }
}

or using the lambda form:

val geocodeListener = Geocoder.GeocodeListener { addresses ->
    // do something with the addresses list
}

After that, you call the getFromLocation() method on a Geocoder instance, surrounding it with an Android SDK check, and providing it the object that you implemented earlier:

val geocoder = Geocoder(context, locale)
if (Build.VERSION.SDK_INT >= 33) {
    // declare here the geocodeListener, as it requires Android API 33
    geocoder.getFromLocation(latitude, longitude, maxResults, geocodeListener)
} else {
    val addresses = geocoder.getFromLocation(latitude, longitude, maxResults)
    // For Android SDK < 33, the addresses list will be still obtained from the getFromLocation() method
}

Upvotes: 9

Related Questions