计算用于覆盖Apple Maps中旅程的时间

我正在研究MKMapView以获得2个位置之间的方向。是否有任何方法可以获得完成这个旅程所需的时间? MKRoute or MKDirection类的内置属性是否可以为我提供时间来支持这个旅程?

任何帮助,将不胜感激。

感谢Vikas

是。

但是,名为calculateETAWithCompletionHandlerMKDirections方法可能有点容易忽略。

一个实现可能如下所示:

 MKDirections *yourDirections = ...; [yourDirections calculateETAWithCompletionHandler:^(MKETAResponse *response, NSError *error) { NSTimeInterval estimatedTravelTimeInSeconds = response.expectedTravelTime; ... }]; 

资源:

https://developer.apple.com/library/mac/documentation/MapKit/Reference/MKDirections_class/Reference/Reference.html

这是Swift 2如果有人正在寻找。 在viewDidLoad之前声明这些variables。

 var request = MKDirectionsRequest() var directions: MKDirections! var locationManager = CLLocationManager() 

像这样创build一个私有函数:

 private func estimateTravelTime(request: MKDirectionsRequest, transportType: MKDirectionsTransportType, source: MKMapItem, destination: MKMapItem, string: String -> ()) { request.source = source request.destination = destination request.transportType = transportType request.requestsAlternateRoutes = false directions = MKDirections(request: request) directions.calculateETAWithCompletionHandler { (response, error) in if let seconds = response?.expectedTravelTime { let minutes = seconds / 60 string(Int(ceil(minutes)).description) } } } 

现在在你的viewDidLoad或viewDidApear(取决于你以后的)使用它是这样的:

  guard let currentLocation = locationManager.location?.coordinate else {return} let source = MKMapItem(placemark: MKPlacemark(coordinate: currentLocation, addressDictionary: nil)) let destination = MKMapItem(placemark: MKPlacemark(coordinate: PUT_YOUR_DESTINATION_HERE, addressDictionary: nil)) estimateTravelTime(request, transportType: .Automobile, source: source, destination: destination) { (string) in print("Minutes for Automobile: \(string) minutes") } estimateTravelTime(request, transportType: .Walking, source: source, destination: destination) { (string) in print("Minutes for Walking: \(string) minutes") } 

为了您的目的地,只需使用经纬度的CLLocationCoordinate2DM,如下所示:

 let destination = CLLocationCoordinate2DMake(44.444551, 26.096641)