calculate time taken to cover a journey in Apple M

2019-03-01 06:40发布

问题:

I am working on MKMapView to get the direction between 2 locations.Is there any way i can get the time it may take in completing this journey?Is there any inbuilt property of MKRoute or MKDirection Class that can provide me time to cover this journey ?

Any help would be appreciated.

Thanks Vikas

回答1:

Yes.

The MKDirections method named calculateETAWithCompletionHandler: can just be a bit easy to overlook, though.

An implementation could look as follows:

MKDirections *yourDirections = ...;

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

Source:

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



回答2:

This is for Swift 2 if anyone is looking. Declare these variables before viewDidLoad.

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

Create a private function like this:

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

Now in your viewDidLoad or viewDidApear (depending on what you're after) use it like this:

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

For your destination just user a CLLocationCoordinate2DMake with the latitude and longitude, something like this:

let destination = CLLocationCoordinate2DMake(44.444551, 26.096641)