在Swift中将GPS坐标转换为城市名称/地址

Jef*_* G. 6 gps cllocation clgeocoder cllocationcoordinate2d swift

我有一个纬度/经度位置,我想转换为Swift中的位置名称String.做这个的最好方式是什么?我相信最好使用reverseGeocodeLocation函数,但不完全确定如何使用.这是我到目前为止:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        var latitude = coord.latitude
        var longitude = coord.longitude

        getCurrentWeatherData("\(longitude)", latitude: "\(latitude)")
        reverseGeocodeLocation(location:coord, completionHandler: { (<#[AnyObject]!#>, <#NSError!#>) -> Void in
            <#code#>
        })

    }
}

func reverseGeocodeLocation(location: CLLocation!, completionHandler: CLGeocodeCompletionHandler!){

}
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 13

您需要编写如下代码:

geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
            placemarks, error in

                if error == nil && placemarks.count > 0 {
                    self.placeMark = placemarks.last as? CLPlacemark
                    self.adressLabel.text = "\(self.placeMark!.thoroughfare)\n\(self.placeMark!.postalCode) \(self.placeMark!.locality)\n\(self.placeMark!.country)"
                    self.manager.stopUpdatingLocation()
                }
            })
Run Code Online (Sandbox Code Playgroud)


Nic*_*ham 5

我使用的是Swift 3/XCode 8

我使用了Benjamin Herzog的答案,但我遇到了一些与可选和强制转换相关的构建错误.

在重写它时,我决定将它封装在一个函数中并对其进行概括,以便可以轻松地将其插入任何地方.

import CoreLocation

func getPlacemark(forLocation location: CLLocation, completionHandler: @escaping (CLPlacemark?, String?) -> ()) {
    let geocoder = CLGeocoder()

    geocoder.reverseGeocodeLocation(location, completionHandler: {
        placemarks, error in

        if let err = error {
            completionHandler(nil, err.localizedDescription)
        } else if let placemarkArray = placemarks {
            if let placemark = placemarkArray.first {
                completionHandler(placemark, nil)
            } else {
                completionHandler(nil, "Placemark was nil")
            }
        } else {
            completionHandler(nil, "Unknown error")
        }
    })

}
Run Code Online (Sandbox Code Playgroud)

使用它:

getPlacemark(forLocation: originLocation) { 
    (originPlacemark, error) in
        if let err = error {
            print(err)
        } else if let placemark = originPlacemark {
            // Do something with the placemark
        }
    })
}
Run Code Online (Sandbox Code Playgroud)