我可以从 Swift 中的地址获取用户的经度和纬度吗?
Can I get the user longitude and latitude from their address in Swift?
正如标题所说,我试图在用户输入应用程序时从他们的地址中推导出用户的位置,但是我还没有找到任何方法来做到这一点。如果有人能帮助我,我将不胜感激。谢谢!
这是一个可以用来从地址获取位置的函数
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)
}
}
}
正如标题所说,我试图在用户输入应用程序时从他们的地址中推导出用户的位置,但是我还没有找到任何方法来做到这一点。如果有人能帮助我,我将不胜感激。谢谢!
这是一个可以用来从地址获取位置的函数
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)
}
}
}