以编程方式打开苹果地图

Open Apple Maps programmatically

我想在我自己的 Swift 应用程序中打开 Apple 地图应用程序,但我只有邮政编码、城市和街道。我没有坐标。我研究了很多,但只有使用协调信息的方法。

您可以将您的地址信息作为 URL 参数传递到 URL 中,用于打开地图应用程序。假设您希望地图应用以白宫为中心打开。

UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=1600,PennsylvaniaAve.,20500")!)

地图应用打开时在搜索字段中显示难看的查询字符串,但它显示了正确的位置。请注意,搜索查询中没有城市和州,只有街道地址和邮政编码。

根据您的需要,一种可能更好的方法是使用 CLGeocoder 获取您拥有的地址信息的 CLLocation。

let geocoder = CLGeocoder()
let str = "1600 Pennsylvania Ave. 20500" // A string of the address info you already have
geocoder.geocodeAddressString(str) { (placemarksOptional, error) -> Void in
  if let placemarks = placemarksOptional {
    print("placemark| \(placemarks.first)")
    if let location = placemarks.first?.location {
      let query = "?ll=\(location.coordinate.latitude),\(location.coordinate.longitude)"
      let path = "http://maps.apple.com/" + query
      if let url = NSURL(string: path) {
        UIApplication.sharedApplication().openURL(url)
      } else {
        // Could not construct url. Handle error.
      }
    } else {
      // Could not get a location from the geocode request. Handle error.
    }
  } else {
    // Didn't get any placemarks. Handle error.
  }
}

使用 Swift 4 和 Xcode 9

顶部:

import CoreLocation

然后:

let geocoder = CLGeocoder()

let locationString = "London"

geocoder.geocodeAddressString(locationString) { (placemarks, error) in
    if let error = error {
        print(error.localizedDescription)
    } else {
        if let location = placemarks?.first?.location {
            let query = "?ll=\(location.coordinate.latitude),\(location.coordinate.longitude)"
            let urlString = "http://maps.apple.com/".appending(query)
            if let url = URL(string: urlString) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
}

Swift 4岁及以上

用这个版本获取Address的坐标,也有直接用地址打开的方法,但是容易出错

import CoreLocation

let myAddress = "One,Apple+Park+Way,Cupertino,CA,95014,USA"
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(myAddress) { (placemarks, error) in
    guard let placemarks = placemarks?.first else { return }
    let location = placemarks.location?.coordinate ?? CLLocationCoordinate2D()
    guard let url = URL(string:"http://maps.apple.com/?daddr=\(location.latitude),\(location.longitude)") else { return }
    UIApplication.shared.open(url)
}

Apple 有一份关于地图 URL 方案的文档。看这里:https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html#//apple_ref/doc/uid/TP40007899-CH5-SW1