Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a city name to coordinates in Swift

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?)
    }
}
like image 282
codeDojo Avatar asked Jan 29 '23 06:01

codeDojo


1 Answers

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

}
like image 142
Leo Dabus Avatar answered Jan 31 '23 23:01

Leo Dabus