iOS Swift坐标函数returns无

iOS Swift coordinates function returns nil

我正在研究将城市(字符串)转换为坐标的函数。但是,当我调用该函数时,结果是“(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())
}

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

这里有两个问题:

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

  2. 一个更微妙的问题是,您正在调用一个 return 异步生成其结果的函数,因此您不能 return 立即获得这些值。相反,您可以使用自己的 completionHandler 模式。

例如:

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