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

标签 ios swift xcode google-maps

我在 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/

相关文章:

iphone - 如果我只支持 iPhone 4+,我还需要标准分辨率资源吗

swift - TableView 的加载和平滑度

ios - 在 RxSwift 的 for 循环中调用多个 API 请求的最佳方式

ios - MapView 不要求位置权限

iphone - 通过 iPhone 应用程序更改壁纸

ios - 无法使用较早的单元测试配置在 Xcode 8 中运行单元测试

javascript - 为什么WKWebView无法运行processingjs脚本?

ios - 将区号与电话号码分开 - iOS

ios - 如何在快速 Storyboard中将 TabBarController 放入另一个 TabBarController 中?

ios - 调用 record() 时 AVAudioRecorder 长延迟