我有一个奇怪的问题。我试图从字符串的地理编码地址,它的工作原理,但我只能在地理编码功能内获得数据。我的代码:
private func getLocationFromAddress(address: String) -> CLLocationCoordinate2D{
let geocoder = CLGeocoder()
var lat = CLLocationDegrees()
var long = CLLocationDegrees()
geocoder.geocodeAddressString(address) { placemark, error in
if let placemark = placemark{
if let lattitude = placemark.first?.location?.coordinate.latitude, let longitude = placemark.first?.location?.coordinate.longitude{
lat = lattitude
long = longitude
print(lat)
}
}else if let err = error{
print(err.localizedDescription)
}
}
print(lat)
return CLLocationCoordinate2D(latitude: lat, longitude: long)
}
在这段代码中,当我在geocoder内部打印变量lat时,它可以工作,但是当我尝试在外部打印它时,它是0.0。为什么它不起作用?而且第二次打印在控制台显示得更早。
函数同步运行,geocodeAddressString(_:)
异步运行。请使用闭包作为完成处理程序。
private func getLocationFromAddress(address: String, completionHandler: @escaping (CLLocationCoordinate2D?) -> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { placemark, error in
if let placemark = placemark {
if let lattitude = placemark.first?.location?.coordinate.latitude, let longitude = placemark.first?.location?.coordinate.longitude {
let coordinate = CLLocationCoordinate2D(latitude: lattitude, longitude: longitude)
completionHandler(coordinate)
}
} else if let err = error{
print(err.localizedDescription)
completionHandler(nil)
}
}
}
getLocationFromAddress(address: someAddress) { coordinate in
if let coordinate = coordinate {
print(coordinate.latitude)
self.coordinate = coordinate
}
}