将城市名称转换为Swift中的坐标 [英] Converting a city name to coordinates in Swift

查看:253
本文介绍了将城市名称转换为Swift中的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上看到了几个问题,但所有这些问题都在Swift 2中老化。
我从Apple网站获得了将城市名称转换为经度和纬度的功能,但我不确定该函数将返回什么因为return语句后没有任何内容),我应该通过什么。

I saw few questions on SO but all of them are old in Swift 2. I got this function from Apple website to convert a city name to latitude and longitude but I am not sure what the function will return (since there is nothing after return statement) and what should I pass. Would someone explain it a lil or show me how to use it please.

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


推荐答案

如下所示:

You can do it as follow:

import CoreLocation

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

用法:

getCoordinateFrom(address: "Rio de Janeiro, Brazil") { 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(coordinate) // CLLocationCoordinate2D(latitude: -22.910863800000001, longitude: -43.204543600000001)
    }

}

这篇关于将城市名称转换为Swift中的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆