ios Swift 中的反向地理编码位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27495328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reverse Geocode Location in Swift
提问by TimWhiting
My input is a latitude and longitude. I need to use the reverseGeocodeLocation
function of swift, to give me the output of the locality. The code I have tried to use is
我的输入是纬度和经度。我需要使用reverseGeocodeLocation
swift的功能,给我本地的输出。我尝试使用的代码是
println(geopoint.longitude)
println(geopoint.latitude)
var manager : CLLocationManager!
var longitude :CLLocationDegrees = geopoint.longitude
var latitude :CLLocationDegrees = geopoint.latitude
var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
println(location)
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error) -> Void in
println(manager.location)
if error != nil {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
println(pm.locality)
}
else {
println("Problem with the data received from geocoder")
}
in the logs I get
在我得到的日志中
//-122.0312186
//37.33233141
//C.CLLocationCoordinate2D
//fatal error: unexpectedly found nil while unwrapping an Optional value
It seems that the CLLocationCoordinate2DMake
function is failing, which then causes the fatal error in the reverseGeocodeLocation
function. Have I mucked up the format somewhere?
似乎CLLocationCoordinate2DMake
函数失败了,然后导致reverseGeocodeLocation
函数中的致命错误。我在某处搞砸了格式吗?
回答by Daij-Djan
you never reverse geocode the location but you pass in manager.location.
您永远不会对位置进行反向地理编码,但您会传入 manager.location。
see:
CLGeocoder().reverseGeocodeLocation(manager.location, ...
看:
CLGeocoder().reverseGeocodeLocation(manager.location, ...
I assume that was a copy&paste mistake and that this is the issue - the code itself looks good - almost ;)
我认为这是一个复制和粘贴错误,这就是问题所在 - 代码本身看起来不错 - 几乎;)
working code
工作代码
var longitude :CLLocationDegrees = -122.0312186
var latitude :CLLocationDegrees = 37.33233141
var location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!
println(location)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
println(location)
guard error == nil else {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
guard placemarks.count > 0 else {
println("Problem with the data received from geocoder")
return
}
let pm = placemarks[0] as! CLPlacemark
println(pm.locality)
})