iOS Swift坐标函数返回nil

时间:2015-01-04 20:12:38

标签: ios swift geocoding

我正致力于将城市(字符串)转换为坐标的功能。但是,当我调用函数时,我得到了"(0.0,0.0)"结果是。它应该是纬度和经度。

请帮帮我。谢谢!

这是功能

func getCoordinates(huidigeLocatie: String) -> (lat: CLLocationDegrees, long: CLLocationDegrees) {

    var lat:CLLocationDegrees
    var long:CLLocationDegrees

    var geocoderHuidigeLocatie = CLGeocoder()

    geocoderHuidigeLocatie.geocodeAddressString(huidigeLocatie, completionHandler:
        {(placemarks: [AnyObject]!, error: NSError!) in

            if error != nil {

                println("Geocode failed with error: \(error.localizedDescription)")

            } else if placemarks.count > 0 {

                let placemark = placemarks[0] as CLPlacemark
                let location = placemark.location

                var lat = location.coordinate.latitude
                var long = location.coordinate.longitude

            }
    })

    return (lat: CLLocationDegrees(), long: CLLocationDegrees())
}

2 个答案:

答案 0 :(得分:3)

这里有两个问题:

  1. 您想要返回实际的latlong变量,而不是CLLocationDegrees()

  2. 更微妙的问题是您正在调用异步返回其结果的函数,因此您无法立即返回值。相反,您可以使用自己的completionHandler模​​式。

  3. 例如:

    func getCoordinates(huidigeLocatie: String, completionHandler: (lat: CLLocationDegrees!, long: CLLocationDegrees!, error: NSError?) -> ()) -> Void {
    
        var lat:CLLocationDegrees
        var long:CLLocationDegrees
    
        var geocoderHuidigeLocatie = CLGeocoder()
    
        geocoderHuidigeLocatie.geocodeAddressString(huidigeLocatie) { (placemarks: [AnyObject]!, error: NSError!) in
    
            if error != nil {
    
                println("Geocode failed with error: \(error.localizedDescription)")
    
                completionHandler(lat: nil, long: nil, error: error)
    
            } else if placemarks.count > 0 {
    
                let placemark = placemarks[0] as CLPlacemark
                let location = placemark.location
    
                let lat = location.coordinate.latitude
                let long = location.coordinate.longitude
    
                completionHandler(lat: lat, long: long, error: nil)
            }
        }
    }
    

    你会这样称呼它:

    getCoordinates(string) { lat, long, error in
        if error != nil { 
            // handle the error here 
        } else {
            // use lat, long here
        }
    }
    
    // but not here
    

答案 1 :(得分:1)

你应该return (lat: lat, long: long)