ios - 使用 MapKit 和 Swift 打开给定地址中的 map

标签 ios swift geolocation mapkit geocoding

我在理解 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/

相关文章:

ios - 如何使用 iOS Simulator 7\XCode 5 测试 iOS 7 之前的用户界面(无需升级 iOS 7 的应用程序)

ios - 如何在 Swift 中正确实现不同 View Controller 之间的协议(protocol)和委托(delegate)?

javascript - 遍历坐标数组并计算距离javascript

mongodb - 带有 golang 和 mongodb 的存储定位器

ios - 如果我返回 Swift,如何在不重新加载 View 的情况下浏览 View

java - Android MapsUtils - 在 map 上点击获取位置

ios - Prepare for segue 是自动调用的

ios - 音频 Blob 在 IOS/Safari 中不起作用

ios - 在后台监听特定的蓝牙特征值

json - 如何在 Swift 中使用 JSON 发出 Alamofire 请求后转换 AnyObject 中的 <AnyObject> 响应?