繁体   English   中英

我可以从 Swift 中的地址获取用户的经度和纬度吗?

[英]Can I get the user longitude and latitude from their address in Swift?

正如标题所说,我试图在用户输入应用程序时从他们的地址中获取用户的位置,但是我还没有找到任何方法来做到这一点。 如果有人可以帮助我,我将不胜感激。 谢谢!

这是一个 function,您可以使用它从地址获取位置

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

所以假设我有这个地址:

let address = "1 Infinite Loop, Cupertino, CA 95014"

用法

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

   print(location.latitude) // result 39.799372
   print(location.longitude) // result -89.644458


}

我们可以从下面的代码中得到coordinate

import UIKit
import CoreLocation


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        getCoordinatesFromPlace(place: "1 Infinite Loop, Cupertino, CA 95014")
    }

    func getCoordinatesFromPlace(place: String){

        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(place) { (placemarks, error) in
            guard
                let placemarks = placemarks,
                let location = placemarks.first?.location?.coordinate
            else {
                // handle no location found
                return
            }
            print(location.latitude)
            print(location.longitude)

        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM