gpt4 book ai didi

ios - 在 Swift 中将城市名称转换为坐标

转载 作者:行者123 更新时间:2023-11-30 10:44:25 25 4
gpt4 key购买 nike

我在 SO 上看到了几个问题,但所有这些问题在 Swift 2 中都是旧的。我从苹果网站获得了这个函数,用于将城市名称转换为纬度和经度,但我不确定该函数将返回什么(因为 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?)
}
}

最佳答案

您可以按如下方式进行:

import CoreLocation

func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
CLGeocoder().geocodeAddressString(address) { completion($0?.first?.location?.coordinate, $1) }
}

用法:

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)
}

}

关于ios - 在 Swift 中将城市名称转换为坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56068028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com