Convert address to coordinates swift Convert address to coordinates swift swift swift

Convert address to coordinates swift


This is pretty easy.

    let address = "1 Infinite Loop, Cupertino, CA 95014"    let geoCoder = CLGeocoder()    geoCoder.geocodeAddressString(address) { (placemarks, error) in        guard            let placemarks = placemarks,            let location = placemarks.first?.location        else {            // handle no location found            return        }        // Use your location    }

You will also need to add and import CoreLocation framework.


You can use CLGeocoder, you can convert address(string) to coordinate and you vice versa, try this:

import CoreLocationvar geocoder = CLGeocoder()geocoder.geocodeAddressString("your address") {    placemarks, error in    let placemark = placemarks?.first    let lat = placemark?.location?.coordinate.latitude    let lon = placemark?.location?.coordinate.longitude    print("Lat: \(lat), Lon: \(lon)")}


Here's what I came up with to return a CLLocationCoordinat2D object:

func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {    let geocoder = CLGeocoder()    geocoder.geocodeAddressString(address) { (placemarks, error) in        guard let placemarks = placemarks,        let location = placemarks.first?.location?.coordinate else {            completion(nil)            return        }        completion(location)    }}

So let's say I've got this address:

let address = "Springfield, Illinois"

Usage

getLocation(from: address) { location in    print("Location is", location.debugDescription)    // Location is Optional(__C.CLLocationCoordinate2D(latitude: 39.799372, longitude: -89.644458))}