使用MapKit和Swift在给定地址打开地图

11

我有点难以理解Swift 3中的Apple MapKit。

我在这里找到了一个示例:如何在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)
}

这个方法完美地运作,但这种情况下我需要使用地址而非坐标

我找到了使用Google Maps的方法,但是我似乎找不到Apple Maps的特定答案,如果它存在的话,我已经漫不经心地翻过去了。

如果有人能帮我理解正确的方法,那就太棒了。我正在使用:

  • Xcode 8.3.1
  • Swift 3.1
  • macOS
  • 目标为 iOS 10+
2个回答

19

你需要使用 地理编码服务 将一个 地址 转换为相应的 地理位置

例如,将此函数添加到您的工具包中:

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

6
您需要使用geoCode从地址获取坐标... 这应该可以工作:
let geocoder = CLGeocoder()

geocoder.geocodeAddressString("ADDRESS_STRING") { (placemarks, error) in

  if error != nil {
    //Deal with error here
  } else if let placemarks = placemarks {

    if let coordinate = placemarks.first?.location?.coordinate {
       //Here's your coordinate
    } 
  }
}

如果您使用if let coordinate = placemarks.first?.location?.coordinate 取代 if place marks.count != 0 并强制解包所有内容,这是更好的做法。 - EmilioPelaez
2
真的。谢谢。;) - Andreza Cristina da Silva

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