Convert address to coordinates swift
Asked Answered
F

6

31

How can I convert a String address to CLLocation coordinates with Swift?

I have no code yet; I looked for a solution but couldn't find any.

Fray answered 16/2, 2017 at 16:16 Comment(0)
M
93

Use CLGeocoder to reverse geocode the address into latitude/longitude coordinates:

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.

Melanymelaphyre answered 16/2, 2017 at 16:34 Comment(1)
where do I use the "location" variable?Dusa
A
17

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

import CoreLocation

var 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)")
}
Adna answered 16/2, 2017 at 16:27 Comment(1)
How can I return a CLLocation value?Purl
C
8

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

}
Certie answered 1/5, 2019 at 5:49 Comment(2)
You should always call a completion handler. If there's no location found, call completion(nil).Fibro
@Fibro Thank you for updating my answer. :)Certie
A
7

Swift 5 and Swift 5.1

import CoreLocation

var 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)") 
}
Azaria answered 20/11, 2019 at 6:43 Comment(0)
M
5

This works

let geocoder = CLGeocoder() 
let address = "8787 Snouffer School Rd, Montgomery Village, MD 20879"
geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
    if((error) != nil){
        print("Error", error ?? "")
    }
    if let placemark = placemarks?.first {
        let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
        print("Lat: \(coordinates.latitude) -- Long: \(coordinates.longitude)")
    }
})
Milla answered 28/9, 2017 at 13:45 Comment(0)
E
0

The CLLocationManager object reports locations as a latitude/longitude pair. While these values uniquely represent any location on the planet, they are not values that users immediately associate with the location. Users are more familiar with names that describe a location, such as street names or city names. The CLGeocoder class lets you convert between geographic coordinates and the user-friendly names associated with that location. You can convert from either a latitude/longitude pair to a user friendly place name, or the other way around.

  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?)
        }
    }
Ethno answered 3/6, 2022 at 1:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.