calculate time taken to cover a journey in Apple Maps

2 Solutions Collect From Internet About “calculate time taken to cover a journey in Apple Maps”

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

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)