I saw few questions on SO but all of them are old in Swift 2. I got this function from Apple website to convert a city name to latitude and longitude but I am not sure what the function will return (since there is nothing after return statement) and what should I pass. Would someone explain it a lil or show me how to use it please.
func getCoordinate( addressString : String,
completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
completionHandler(location.coordinate, nil)
return
}
}
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
You can do it as follow:
import CoreLocation
func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
CLGeocoder().geocodeAddressString(address) { completion($0?.first?.location?.coordinate, $1) }
}
Usage:
let address = "Rio de Janeiro, Brazil"
getCoordinateFrom(address: address) { coordinate, error in
guard let coordinate = coordinate, error == nil else { return }
// don't forget to update the UI from the main thread
DispatchQueue.main.async {
print(address, "Location:", coordinate) // Rio de Janeiro, Brazil Location: CLLocationCoordinate2D(latitude: -22.9108638, longitude: -43.2045436)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With