安卓地理编码器void getFromLocation如何获取地址?

4
我在我的Android活动中有一个Geocoder类,其中包含Google地图。我需要使用反向地理编码。
getFromLocation(double latitude, double longitude, int maxResults, Geocoder.GeocodeListener listener)

该方法声明为void,但必须返回地址列表。根据谷歌的说法,应按以下方式操作:
提供一个地址数组,尝试描述给定纬度和经度周围的区域。返回的地址应针对提供给该类构造函数的语言环境进行本地化。
如果此方法是void类型,如何获得地址列表?

通过实现“Geocoder.GeocodeListener”并将该实例作为最后一个参数传递给“getFromLocation”。 - Michael
2个回答

8

(Kotlin)

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

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

或使用lambda形式:

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

接下来,在一个Android SDK检查的范围内,调用Geocoder实例上的getFromLocation()方法,并提供您之前实现的对象:

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
}

很好的回答。我想提一下,我在使用Geocoder.GeocodeListener和Koin时遇到了问题 - Koin抛出了运行时异常“找不到类Geocoder.GeocodeListener”。不确定原因是什么,但现在只能回滚到使用弃用的方法。也许Koin应该修复一些东西。 - Myroslav
这种情况发生是因为你可能在 Android 设备/模拟器上运行了代码,而它的 SDK 版本低于 33(即 Android 13),没有完全隔离 SDK if-check 的第一分支内的 Geocoder.GeocodeListener 的使用。新的方法仅适用于 SDK ≥ 33,而对于较低版本,弃用的方法仍在使用中。 - wolfOnix
实际上不是这样的,对于 Android < 13,我使用了“旧”的方法。 - Myroslav

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接