Convert GPS coordinates to a city name / address in Swift

守給你的承諾、 提交于 2019-12-05 07:18:38

You need to write the code like this:

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()
                }
            })
Nick Graham

I am using Swift 3 / XCode 8

I used Benjamin Herzog's answer but I ran into some build errors related to optional and casting.

In rewriting it, I decided to encapsulate it in a function and generalize it so it can easily be plugged in anywhere.

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

}

Using it:

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

please check this answer.

 func getAddressFromGeocodeCoordinate(coordinate: CLLocationCoordinate2D) {
    let geocoder = GMSGeocoder()
    geocoder.reverseGeocodeCoordinate(coordinate) { response , error in

      //Add this line
      if let address = response!.firstResult() {
        let lines = address.lines! as [String]
        print(lines)

      }
    }
  }

Swift Code to get address of the placemark, nicely Formatted

let address = ABCreateStringWithAddressDictionary(placemark.addressDictionary!, false).componentsSeparatedByString("\n").joinWithSeparator(", ")

print(address!)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!