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
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:
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)
来源:https://stackoverflow.com/questions/23084304/calculate-time-taken-to-cover-a-journey-in-apple-maps