【问题标题】:Open map in a given address using MapKit and Swift使用 MapKit 和 Swift 在给定地址打开地图
【发布时间】:2017-10-10 15:48:22
【问题描述】:

我在理解 Swift 3 中的 Apple MapKit 时遇到了一些麻烦。

我在这里找到了一个例子:How to open maps App programmatically with coordinates in 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)
}

除了在这种情况下我需要使用 address 而不是 coordinates 之外,这绝对有效。

我已经找到了使用谷歌地图执行此操作的方法,但我似乎无法找到 Apple Maps 的具体答案,如果它存在,我已经完成了对它的了解。

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

  • Xcode 8.3.1
  • 斯威夫特 3.1
  • macOS
  • 面向 iOS 10+

【问题讨论】:

    标签: ios swift geolocation mapkit geocoding


    【解决方案1】:

    您需要使用地理编码服务地址转换为对应的地理位置

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

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

    【讨论】:

      【解决方案2】:

      您需要使用 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?.coordinateif place marks.count != 0 好,然后强制展开所有内容。
      • 是的。谢谢。 ;)
      猜你喜欢
      • 1970-01-01
      • 2016-01-05
      • 2014-03-11
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      相关资源
      最近更新 更多