Convert address to coordinates swift

匆匆过客 提交于 2019-12-02 16:50:48

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

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

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!