calculate time taken to cover a journey in Apple Maps

*爱你&永不变心* 提交于 2019-12-02 05:05:48

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!