以编程方式打开苹果地图

13

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


你可以使用谷歌的地理编码 API 将你的地址转换为坐标。https://developers.google.com/maps/documentation/geocoding/intro - Ollie
4个回答

22
您可以在打开地图应用程序的URL中将地址信息作为URL参数传递。比如,如果您想让地图应用程序以白宫为中心打开。请参考以下示例代码:

http://maps.google.com/maps?q=1600+Pennsylvania+Ave+NW,+Washington,+DC+20500

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

地图应用程序打开时会显示一个丑陋的查询字符串在搜索框中,但它会显示正确的位置。请注意,搜索查询中缺少城市和州的信息,只有街道地址和邮政编码。
根据您的需求,可能更好的方法是使用CLGeocoder获取已知地址信息的CLLocation。请参考CLGeocoder
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
在字符串中,您可以使用%20代替空格来分隔单词,例如“1600%20Pennsylvania%20Ave.%2020500”将适用于您答案的第一个选项,并且会在地图中打开,类似于“1600 Pennsylvania Ave. 20500”。 - JCode
+1 @JCode,查询应该被“编码”,以便空格和其他特殊字符能够正确解析。 - Abhishek Ghosh

11

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

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


5

Swift 5:直接打开地图应用程序

///Opens text address in maps
static func openAddressInMap(address: String?){
    guard let address = address else {return}
    
    let geoCoder = CLGeocoder()
    geoCoder.geocodeAddressString(address) { (placemarks, error) in
        guard let placemarks = placemarks?.first else {
            return
        }
        
        let location = placemarks.location?.coordinate
        
        if let lat = location?.latitude, let lon = location?.longitude{
            let destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon)))
            destination.name = address
            
            MKMapItem.openMaps(
                with: [destination]
            )
        }
    }
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接