Convert address to coordinates swift

徘徊边缘 提交于 2019-12-03 02:51:56

问题


How can I convert a String address to CLLocation coordinates with Swift? I have no code yet, I looked for a solution but I didn't find anyone yet.

Thanks.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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

}



回答5:


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


来源:https://stackoverflow.com/questions/42279252/convert-address-to-coordinates-swift

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