我有一个纬度/经度位置,我想将其转换为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!){
}
答案 0 :(得分: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()
}
})
答案 1 :(得分:5)
我正在使用Swift 3 / XCode 8
我使用Benjamin Herzog's answer但是遇到了一些与可选和强制转换相关的构建错误。
在重写它时,我决定将它封装在一个函数中并对其进行概括,以便可以轻松插入任何地方。
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")
}
})
}
使用它:
getPlacemark(forLocation: originLocation) {
(originPlacemark, error) in
if let err = error {
print(err)
} else if let placemark = originPlacemark {
// Do something with the placemark
}
})
}
答案 2 :(得分:4)
请检查这个答案。
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)
}
}
}
答案 3 :(得分:0)
Swift Code获取地标的地址,格式良好
let address = ABCreateStringWithAddressDictionary(placemark.addressDictionary!, false).componentsSeparatedByString("\n").joinWithSeparator(", ")
print(address!)