如何获得两点之间的行车距离?

时间:2013-07-18 06:02:48

标签: iphone objective-c core-location

我想创建一个可以计算A点到B点之间行驶距离的应用程序。我知道CLLocationdistanceFromLocation:来计算2点之间的距离,但它只计算直线从A点到B点的线是否有办法计算2点之间的行驶距离?怎么样?有样品吗?

由于

2 个答案:

答案 0 :(得分:2)

我认为iOS中没有任何功能,distanceFromLocation会给出两个坐标之间的空中距离。

但是,您可以使用google APIS来计算道路距离。

答案 1 :(得分:2)

斯威夫特3:

func routingDistance(userNotation: CLLocation, destinationLocation: CLLocation, completion: @escaping (CLLocationDistance) -> Void) {
    let request:MKDirectionsRequest = MKDirectionsRequest()

    // source and destination are the relevant MKMapItems
    let sourceS = CLLocationCoordinate2D(latitude: userNotation.coordinate.latitude, longitude: userNotation.coordinate.longitude)
    let destinationD = CLLocationCoordinate2D(latitude: destinationLocation.coordinate.latitude, longitude: destinationLocation.coordinate.longitude)
    let sourcePM = MKPlacemark(coordinate: sourceS)
    let destinationPM = MKPlacemark(coordinate: destinationD)
    request.source = MKMapItem(placemark: sourcePM)
    request.destination = MKMapItem(placemark: destinationPM)

    // Specify the transportation type
    request.transportType = MKDirectionsTransportType.automobile;

    // If you're open to getting more than one route,
    // requestsAlternateRoutes = true; else requestsAlternateRoutes = false;
    request.requestsAlternateRoutes = true

    let directions = MKDirections(request: request)

    directions.calculate { (response, error) in
        if let response = response, let route = response.routes.first {
            completion(route.distance)
        }
    }
}