I have a latitude/longitude location that I want to convert to the location name String in Swift. What is the best way to do this? i believe it's best to use the reverseGeocodeLocation function but not exactly sure how to. This is what I have so far:
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!){
}
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!)
来源:https://stackoverflow.com/questions/26226602/convert-gps-coordinates-to-a-city-name-address-in-swift