cod*_*ojo 4 xcode google-maps ios swift
我在 SO 上看到的问题很少,但它们在 Swift 2 中都是旧的。我从 Apple 网站获得了这个函数,用于将城市名称转换为纬度和经度,但我不确定该函数将返回什么(因为 return 语句之后没有任何内容) 我应该通过什么。有人会解释一下吗,或者请告诉我如何使用它。
func getCoordinate( addressString : String,
completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
completionHandler(location.coordinate, nil)
return
}
}
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
import CoreLocation
func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
CLGeocoder().geocodeAddressString(address) { completion($0?.first?.location?.coordinate, $1) }
}
Run Code Online (Sandbox Code Playgroud)
用法:
let address = "Rio de Janeiro, Brazil"
getCoordinateFrom(address: address) { coordinate, error in
guard let coordinate = coordinate, error == nil else { return }
// don't forget to update the UI from the main thread
DispatchQueue.main.async {
print(address, "Location:", coordinate) // Rio de Janeiro, Brazil Location: CLLocationCoordinate2D(latitude: -22.9108638, longitude: -43.2045436)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |