【问题标题】:Reverse Geocode Location in Swift [closed]Swift中的反向地理编码位置[关闭]
【发布时间】:2015-02-14 05:09:41
【问题描述】:

我的输入是纬度和经度。我需要使用 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。

标签: ios swift cllocationmanager reverse-geocoding


【解决方案1】:

您永远不会对位置进行反向地理编码,但您会传入 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)
    })

【讨论】:

  • 我想要详细的地址,例如街道名称、城市、州、国家/地区。您的帖子仅提供城市..
  • 您可以在此处查看附加属性:developer.apple.com/documentation/corelocation/clplacemark
  • 这一行没有意义“ if error != nil ”。如果会发生错误,则它不会为零。
  • 嗨,对不起,我害怕不关注。 if error != nil { return } 就像提前退出一样,不是吗?
  • @BananZ 覆盖了编辑拒绝,其他人都同意并接受了它。没关系,不会改变任何东西。 ——但你的编辑不应该进行。如果你写了'让我们使用警戒语句让事情更清晰 TBH ;) 会更好——无论如何,谢谢。也许有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多