通过MapKit获取道路距离 - Swift

时间:2015-02-08 18:51:05

标签: ios swift mapkit

如果我想获得道路距离,我应该考虑哪些课程?

我希望能得到的是从A点到B点的道路距离,我不需要显示分步指示和地图。

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:13)

您需要发出MKDirections个请求。从calculateDirectionsWithCompletionHandler开始,您将获得MKDirectionsResponse。这个routes数组MKRoutes。每条路线都有distance(即道路距离)属性。

    let source = MKMapItem( placemark: MKPlacemark(
        coordinate: CLLocationCoordinate2DMake(-41.27, 173.28),
        addressDictionary: nil))
    let destination = MKMapItem(placemark: MKPlacemark(
        coordinate: CLLocationCoordinate2DMake(-41.11, 173),
        addressDictionary: nil))

    let directionsRequest = MKDirectionsRequest()
    directionsRequest.source = source
    directionsRequest.destination = destination

    let directions = MKDirections(request: directionsRequest)

    directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
        print(error)
        let distance = response!.routes.first?.distance // meters
        print("\(distance! / 1000)km")
    }