【问题标题】:Reverse geocoding explanation反向地理编码解释
【发布时间】:2019-05-15 13:51:46
【问题描述】:

我在 Swift 4 中找到了一段很棒的反向地理编码代码:Reverse geocoding in Swift 4

我不明白这里发生了什么:

func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ())  {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
}

从这里调用它之后:

geocode(latitude: -22.963451, longitude: -43.198242) { placemark, error in
 guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
    //  update UI here
    print("address1:", placemark.thoroughfare ?? "")
    print("address2:", placemark.subThoroughfare ?? "")
    print("city:",     placemark.locality ?? "")
    print("state:",    placemark.administrativeArea ?? "")
    print("zip code:", placemark.postalCode ?? "")
    print("country:",  placemark.country ?? "")       
 }
}

谁能解释一下。

【问题讨论】:

    标签: ios swift mapkit geocoding


    【解决方案1】:
    # Gets latitude, longitude and a completion block
    func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ()) 
    {
        # Calls system function to resolve the coordinates
        CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude))
        {
            # $0 is the placemarks array so this returns the first value of the placemarks array
            # $1 is the error 
            completion($0?.first, $1)
    
        }
    }
    

    Geocode 函数获取纬度和经度以及完成块。它将坐标传递给 CLGeocoder().reverseGeocodeLocation 函数并返回带有完成块的第一个地标。

    reverseGeocodeLocation 的方法签名是

    func reverseGeocodeLocation(_ location: CLLocation, completionHandler: @escaping CLGeocodeCompletionHandler)

    而完成处理程序被定义为

    typealias CLGeocodeCompletionHandler = ([CLPlacemark]?, Error?) -> Void
    

    如您所见 [CLPlacemark]?是 CLPlacemarks 的可选数组。

    【讨论】:

    • 谢谢 :) 那么如果完成块返回 $1 会发生什么。我需要在此处添加错误处理程序吗?
    • 您可以在 func geocode() 中检查错误,它会以正确的名称返回错误。
    • 其实你已经在使用 guard let placemark = placemark, error == nil else { return } 行了。
    猜你喜欢
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多