我想创建一个可以计算A点到B点之间行驶距离的应用程序。我知道CLLocation
有distanceFromLocation:
来计算2点之间的距离,但它只计算直线从A点到B点的线是否有办法计算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)
}
}
}