Swift で場所を逆ジオコードする [closed] 質問する

Swift で場所を逆ジオコードする [closed] 質問する

入力は緯度と経度です。SwiftreverseGeocodeLocationの機能を使って、地域を出力する必要があります。私が試したコードは次のとおりです。

            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。どこかでフォーマットを間違えたのでしょうか?

ベストアンサー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)
    })

おすすめ記事