在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?)

}

}

回答:

您可以按照以下步骤进行操作:

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)

}

}

以上是 在Swift中将城市名称转换为坐标 的全部内容, 来源链接: utcz.com/qa/397553.html

回到顶部