繁体   English   中英

地理编码器 - getFromLocation() 已弃用

[英]Geocoder - getFromLocation() deprecated

我收到一条消息,指出此 function(或其构造函数)已被弃用。 该 function 有一个新的构造函数,它接受一个附加参数'Geocoder.GeocodeListener listener' ,但该新构造函数需要 API 级别 33 及以上。 低API级别怎么办,怎么解决?

在此处输入图像描述

由于这在 API 级别 33 中已弃用,我相信这是较低 API 级别的唯一选择。

我认为处理这种弃用的最干净的方法是将 getFromLocation 移动到新的扩展 function 中并像这样添加 @Suppress("DEPRECATION") :

@Suppress("DEPRECATION")
fun Geocoder.getAddress(
    latitude: Double,
    longitude: Double,
    address: (android.location.Address?) -> Unit
) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        getFromLocation(latitude, longitude, 1) { address(it.firstOrNull()) }
        return
    }

    try {
        address(getFromLocation(latitude, longitude, 1)?.firstOrNull())
    } catch(e: Exception) {
        //will catch if there is an internet problem
        address(null)
    }
}

这是如何使用:

    Geocoder(requireContext(), Locale("in"))
        .getAddress(latlng.latitude, latlng.longitude) { address: android.location.Address? ->
        if (address != null) {
            //do your logic
        }
    }

官方文档- 使用getFromLocation(double, double, int, android.location.Geocoder.GeocodeListener)来避免阻塞等待结果的线程。

例子:

//Variables
val local = Locale("en_us", "United States")
val geocoder = Geocoder(this, local)
val latitude = 18.185600
val longitude = 76.041702
val maxResult = 1


//Fetch address from location
geocoder.getFromLocation(latitude,longitude,maxResult,object : Geocoder.GeocodeListener{
 override fun onGeocode(addresses: MutableList<Address>) {

    // code                      
 }
 override fun onError(errorMessage: String?) {
     super.onError(errorMessage)

 }

})

方法getFromLocationName仍然存在,但现在需要“边界框”参数lowerLeftLatitudelowerLeftLongitudeupperRightLatitudeupperRightLongitude
将“边界框”设置为视图边界坐标应该可行。

@SuppressWarnings({"deprecation", "RedundantSuppression"})
...

Geocoder geoCoder = new Geocoder(requireContext());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    geoCoder.getFromLocationName(
            geocode, maxResults,
            lowerLeftLatitude, lowerLeftLongitude,
            upperRightLatitude,upperRightLongitude,
            addresses -> {
                Address bestMatch = (addresses.isEmpty() ? null : addresses.get(0));
                updatePosition(item, bestMatch);
            });
} else {
    try {
        List<Address> addresses = geoCoder.getFromLocationName(geocode, maxResults);
        Address bestMatch = (addresses.isEmpty() ? null : addresses.get(0));
        updatePosition(item, bestMatch);
    } catch (IOException e) {
        if (mDebug) {Log.e(LOG_TAG, e.getMessage());}
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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