android geocoder void getfromlocation 如何获取地址?

Mal*_*alo 4 android google-geocoder

我的 android 活动中有地理编码器类,其中包含谷歌地图

我需要使用反转地理编码

getFromLocation(double latitude, double longitude, int maxResults, Geocoder.GeocodeListener listener)
Run Code Online (Sandbox Code Playgroud)

这个方法有无效声明,但必须返回地址列表,根据谷歌的说法,他们说要执行以下操作

提供一组地址,尝试描述紧邻给定纬度和经度周围的区域。返回的地址应该针对提供给此类构造函数的区域设置进行本地化。

如果此方法是 void 类型,如何获取地址列表?

小智 8

(科特林)

当实现抽象方法时,地址列表将可用onGeocode()。要访问地址列表,您应该声明一个带有GeocodeListener实例实现的变量:

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

或使用 lambda 形式:

val geocodeListener = Geocoder.GeocodeListener { addresses ->
    // do something with the addresses list
}
Run Code Online (Sandbox Code Playgroud)

之后,您在实例getFromLocation()上调用该方法Geocoder,用 Android SDK 检查包围它,并为其提供您之前实现的对象:

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
}
Run Code Online (Sandbox Code Playgroud)