以编程方式在iOS8,Xcode 7,Swift 2

时间:2015-11-18 18:31:17

标签: iphone ios8 swift2 xcode7 apple-maps

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

3 个答案:

答案 0 :(得分:14)

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

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.
  }
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

雨燕4

UIApplication.shared.open(URL(string:"http://maps.apple.com/?address=yourAddress")!)