【问题标题】:Converting a city name to coordinates in Swift在 Swift 中将城市名称转换为坐标
【发布时间】:2017-11-12 01:19:49
【问题描述】:

我看到一些关于 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?)
    }
}

【问题讨论】:

    标签: ios swift xcode google-maps


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      执行诸如获取城市坐标之类的异步操作无法将值作为函数结果返回。您必须拨打电话,开展您的业务,然后等待它调用您的完成处理程序。上面代码中的参数completionHandler 是什么。你传入一个闭包(一段代码),一旦结果准备好就执行。你可以这样使用它:

      getCoordinate(addressString: someString) { coordinate, error in
        if error != nil {
          //display error
          return
        } else {
          //at this point `coordinate ` contains a valid coordinate. 
          //Put your code to do something with it here
          print("resulting coordinate = (\(coordinate.latitude),\(coordinate.longitude))")
        }
      }
      

      请注意,对于 Swift 3,您应该让函数抛出而不是返回结果或错误。

      【讨论】:

      • 我真的很感激你所做的,但是如果我只是想传递一个城市名称来获取位置,因为我不确定如何使用它来传递代码块。请您告诉我我需要使用的确切代码,我将不胜感激。
      • 你写的那段代码,我不确定是解释还是真正的功能,我试图把它放在我的代码中,我得到了很多错误。
      • 这里的主要问题只是缺少右括号,这解释了为什么 OP 有很多错误。顺便说一句,命名 CLLocationCoordinate2D 位置具有误导性,而且您还忘记提及在调用异步方法时 OP 需要返回主线程来更新 UI。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多