簡體   English   中英

以編程方式打開 Apple 地圖

[英]Open Apple Maps programmatically

我想在我自己的 Swift 應用程序中打開 Apple Maps 應用程序,但我只有郵政編碼、城市和街道。 我沒有坐標。 我研究了很多,但只有使用協調信息的方法。

您可以在打開地圖應用程序的 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 及以上

用這個版本獲取地址的坐標,也有直接用地址打開的方法,但是容易出錯

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 有一個關於 Map URL Scheme 的文檔。 看這里: https : //developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html#//apple_ref/doc/uid/TP40007899-CH5-SW1

使用 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)
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM