我在这里找到了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 ?? "")
}
}
任何人都可以提供一个解释。
答案 0 :(得分:0)
# 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的可选数组。