【问题标题】:android geocoder void getfromlocation how to get addresses?android geocoder void getfromlocation 如何获取地址?
【发布时间】:2022-12-07 12:53:29
【问题描述】:

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

我需要使用反转地理编码

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

此方法具有 void 声明但必须返回地址列表,根据谷歌他们说要执行以下操作

提供一组地址,这些地址试图描述紧邻给定纬度和经度的区域。返回的地址应该针对提供给此类构造函数的语言环境进行本地化。

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

【问题讨论】:

  • 通过实现 Geocoder.GeocodeListener 并将实例作为最后一个参数传递给 getFromLocation

标签: android google-geocoder


【解决方案1】:

(科特林)

地址列表将在实现抽象方法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
}

之后,您在 Geocoder 实例上调用 getFromLocation() 方法,用 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
}

【讨论】:

  • 很好的答案。我想提一下,我在使用 Geocoder.GeocodeListener 和 Koin 时遇到了问题 - Koin 抛出运行时异常“找不到类 Geocoder.GeocodeListener”。不确定这是什么原因,但现在只是回滚到使用不推荐使用的方法。也许 Koin 应该解决一些问题。
  • 发生这种情况是因为您可能在 SDK 级别低于 33 (Android 13) 的 Android 设备/模拟器上运行代码,而没有在 SDK if-check 的第一个分支内完全隔离对 Geocoder.GeocodeListener 的任何使用。新方法仅适用于 SDK ≥ 33,而对于较低级别,已弃用的方法仍在使用。
  • 实际上不是,对于 Android < 13,我使用了“旧”方法。
【解决方案2】:
@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}"
                            )
                        )
                    }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    相关资源
    最近更新 更多