简体   繁体   中英

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?

@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}"
                            )
                        )
                    }
            }
        }
    }

(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
}

(Probably this may be late for you, but maybe the answer will be helpful for someone in the future:)) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM