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

Open map in a given address using MapKit and Swift

我在理解 Swift 3.

中的 Apple MapKit 时遇到了一些问题

我在这里找到了一个例子:

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 地图执行此操作的方法,但我似乎无法找到 Apple 地图的具体答案,如果它存在,我已经完成了。

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

您需要使用 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
    } 
  }
}

您需要使用地理编码服务地址转换为相应的地理定位 .

例如,将此功能添加到您的工具包中:

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