Reverse Geocode Location in Swift [closed]

喜夏-厌秋 提交于 2020-01-09 06:21:22

问题


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

            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 CLLocationCoordinate2DMakefunction is failing, which then causes the fatal error in the reverseGeocodeLocation function. Have I mucked up the format somewhere?


回答1:


you never reverse geocode the location but you pass in manager.location.

see: 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)

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


来源:https://stackoverflow.com/questions/27495328/reverse-geocode-location-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!