将地址转换为swift坐标

问题描述 投票:10回答:4

如何使用Swift将String地址转换为CLLocation坐标?我还没有代码,我找了一个解决方案,但我还没找到任何人。

谢谢。

ios swift coordinates core-location
4个回答
58
投票

这很简单。

    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
    }

您还需要添加和导入CoreLocation框架。


7
投票

你可以使用CLGeocoder,你可以将地址(字符串)转换为坐标,反之亦然,试试这个:

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
投票

这有效

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

0
投票

这是我想出的返回CLLocationCoordinat2D对象的内容:

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

所以,假设我有这个地址:

let address = "Springfield, Illinois"

用法

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

}
© www.soinside.com 2019 - 2024. All rights reserved.