我在理解 Swift 3 中 Apple 的 MapKit 时遇到了一些麻烦。
我在这里找到了一个例子:How to open maps App programmatically with coordinates in swift?
public func openMapForPlace(lat:Double = 0, long:Double = 0, placeName:String = "") {
let latitude: CLLocationDegrees = lat
let longitude: CLLocationDegrees = long
let regionDistance:CLLocationDistance = 100
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = placeName
mapItem.openInMaps(launchOptions: options)
}
除了在这种情况下我需要使用地址而不是坐标之外,这绝对可以正常工作。
我已经找到使用谷歌地图执行此操作的方法,但我似乎无法找到适用于 Apple map 的具体答案,如果它存在,我已经完成了它。
如果有人能帮助我理解正确的方法是什么,那就太棒了。我正在使用:
- Xcode 8.3.1
- swift 3.1
- 苹果操作系统
- 以 iOS 10+ 为目标
最佳答案
您需要使用地理编码服务 将地址 转换为相应的地理位置。
例如,将此功能添加到您的工具包中:
func coordinates(forAddress address: String, completion: @escaping (CLLocationCoordinate2D?) -> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) {
(placemarks, error) in
guard error == nil else {
print("Geocoding error: \(error!)")
completion(nil)
return
}
completion(placemarks.first?.location?.coordinate)
}
}
然后像这样使用它:
coordinates(forAddress: "YOUR ADDRESS") {
(location) in
guard let location = location else {
// Handle error here.
return
}
openMapForPlace(lat: location.latitude, long: location.longitude)
}
关于ios - 使用 MapKit 和 Swift 打开给定地址中的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918842/