【发布时间】:2021-06-20 15:27:17
【问题描述】:
我是初学者,很抱歉我的问题。
我在数据文件中有地图和注释。
现在我希望用户能够使用表单注册地址。
我如何从普通地址转到一个
location: CLLocationCoordinate2D(latitude: 48.8566, longitude: 2.3522)
感谢您的帮助
【问题讨论】:
标签: swiftui mapkit mapkitannotation
我是初学者,很抱歉我的问题。
我在数据文件中有地图和注释。
现在我希望用户能够使用表单注册地址。
我如何从普通地址转到一个
location: CLLocationCoordinate2D(latitude: 48.8566, longitude: 2.3522)
感谢您的帮助
【问题讨论】:
标签: swiftui mapkit mapkitannotation
Core Location 有一个“地理编码器”,它将获取街道地址并将其转换为 CLLocationCoordinate2D。
这是来自 Apple 官方文档 (https://developer.apple.com/documentation/corelocation/converting_between_coordinates_and_user-friendly_place_names):
func getCoordinate( addressString : String,
completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
completionHandler(location.coordinate, nil)
return
}
}
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
注意,前面的函数使用回调函数,是一个异步函数。这意味着它不会立即返回 - 相反,它会在未来不确定的时间结束,并在结束时调用回调函数。
由于您标记了问题 SwiftUI,以下是 SwiftUI 的一个简单示例:
import SwiftUI
import MapKit
class LocationManager : ObservableObject {
@Published var location : CLLocationCoordinate2D?
func convertAddress(address: String) {
getCoordinate(addressString: address) { (location, error) in
if error != nil {
//handle error
return
}
DispatchQueue.main.async {
self.location = location
}
}
}
private func getCoordinate(addressString : String,
completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
completionHandler(location.coordinate, nil)
return
}
}
completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
}
}
}
struct ContentView: View {
@State var addressString = "1600 Pennsylvania Ave, Washington D.C."
@StateObject private var locationManager = LocationManager()
var body: some View {
VStack {
Text("Address: \(addressString)")
if let location = locationManager.location {
Text("Lat: \(location.latitude) Long: \(location.longitude)")
}
}.onAppear {
locationManager.convertAddress(address: addressString)
}
}
}
【讨论】: