关于ios:使用MapKit和Swift在给定地址中打开地图

Open map in a given address using MapKit and Swift

在Swift 3中理解Apple的MapKit有点麻烦。

我在这里找到了一个示例:如何使用坐标快速编程地打开地图应用程序?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
  • 斯威夫特3.1
  • 苹果系统
  • 定位iOS 10

您需要使用地址解析服务将地址转换为相应的地理位置。

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

1
2
3
4
5
6
7
8
9
10
11
12
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)
    }
}

,然后像这样使用它:

1
2
3
4
5
6
7
8
coordinates(forAddress:"YOUR ADDRESS") {
    (location) in
    guard let location = location else {
        // Handle error here.
        return
    }
    openMapForPlace(lat: location.latitude, long: location.longitude)
}


您需要使用geoCode来从地址获取坐标...这应该起作用:

1
2
3
4
5
6
7
8
9
10
11
12
13
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
    }
  }
}