Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get road distance with MapKit - Swift

Tags:

ios

swift

mapkit

What are the classes I should look into if I want to get road distance?

All I want to be able to get is the road-distance from point A to point B, I don't need to show step by step directions nor the map.

Any suggestions?

Thanks

like image 810
fs_tigre Avatar asked Feb 08 '15 18:02

fs_tigre


1 Answers

You need to make a MKDirections request. From calculateDirectionsWithCompletionHandler you will get a MKDirectionsResponse. This has a routes array of MKRoutes. Each route has a distance (i.e. road distance) property.

    let source = MKMapItem( placemark: MKPlacemark(
        coordinate: CLLocationCoordinate2DMake(-41.27, 173.28),
        addressDictionary: nil))
    let destination = MKMapItem(placemark: MKPlacemark(
        coordinate: CLLocationCoordinate2DMake(-41.11, 173),
        addressDictionary: nil))

    let directionsRequest = MKDirectionsRequest()
    directionsRequest.source = source
    directionsRequest.destination = destination

    let directions = MKDirections(request: directionsRequest)

    directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
        print(error)
        let distance = response!.routes.first?.distance // meters
        print("\(distance! / 1000)km")
    }
like image 135
Onato Avatar answered Oct 09 '22 08:10

Onato