在Swift中反向地理编码位置

26

我的输入是一组纬度和经度。我需要使用swift的reverseGeocodeLocation函数,以便输出该地区的位置信息。我尝试使用的代码如下:

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

在日志中我得到的信息是

//-122.0312186
//37.33233141
//C.CLLocationCoordinate2D
//fatal error: unexpectedly found nil while unwrapping an Optional value

似乎CLLocationCoordinate2DMake函数出现了问题,导致在reverseGeocodeLocation函数中发生了致命错误。我是否在某个地方搞砸了格式?


你没有创建必须作为位置传递的CLLocation。在你的情况下,位置变量是一个CLLocationCoordinate2D,意味着它是一个坐标。你需要从你创建的坐标中创建CLLocation而不是CLLocationCoordinate2D。 - Natasha
1个回答

70

你从来没有对位置进行反地理编码,但是你传递了manager.location。

参见: CLGeocoder().reverseGeocodeLocation(manager.location, ...

我假设这是一个复制粘贴错误并且这就是问题所在-代码本身看起来很好-几乎 ;)

有效的代码

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

我想要详细的地址,比如街道名称、城市、州和国家。你的帖子只提供了城市。 - Jayprakash Dubey
您可以在此处查看附加属性:https://developer.apple.com/documentation/corelocation/clplacemark - Niko Klausnitzer
这行代码“if error != nil”没有意义。如果出现错误,那么它就不会是nil。 - ShadeToD
嗨,抱歉我不太明白。if error!= nil { return } 就像是提前退出,对吧? - Daij-Djan
我已经改为防御式编程以提高可读性。希望这能有所帮助。 - BananZ
1
@BananZ 覆盖了其他人拒绝编辑的内容,所有人都同意并接受了它。这没问题,也没有改变什么。-- 但是你的编辑不应该被进行。如果你写了“让我们使用守卫语句使事情更清晰 TBH ;)”,那会更好。-- 无论如何,谢谢。也许有所帮助。 - Daij-Djan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接