How do I calculate the driving distance between two addresses on a map in MapKit?

How do I calculate the driving distance between two addresses on a map view in MapKit?

Hi brower,
to get the distance between two points in MapKit, you can use the distance method as in this snippet below

let p1 = CLLocation(latitude: 148.0001, longitude: -19.0001)
let p2 = CLLocation(latitude: 148.0002, longitude: -19.0002)
let distance = p2.distance(from: p1)

print(distance)

cheers,

Jayant

I actually need the driving distance. I figured out to use MKDirections.

Hi brower,
That’s great, now finding the driving distance is easier. When you look up directions on Apple Maps, you get options to choose from that include tolls or no tolls and duration based on traffic and distance. Where you select one and get directions. With that in mind, lets have a look.

First let’s get a request
let request = MKDirectionsRequest()

We have the co-ordinates as p1 and p2

let sourceP         = CLLocationCoordinate2DMake(p1.coordinate.latitude, p1.coordinate.longitude)
let destP           = CLLocationCoordinate2DMake(p2.coordinate.latitude, p2.coordinate.longitude)
let source          = MKPlacemark(coordinate: sourceP)
let destination     = MKPlacemark(coordinate: destP)
request.source      = MKMapItem(placemark: source)
request.destination = MKMapItem(placemark: destination)

// Specify the transportation type
request.transportType = MKDirectionsTransportType.automobile;

// If you're open to getting more than one route,
// requestsAlternateRoutes = true; else requestsAlternateRoutes = false;
request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)

// Now we have the routes, we can calculate the distance using
    directions.calculate { (response, error) in
    if let response = response, let route = response.routes.first {
        print(route.distance) // You could have this returned in an async approach
    }
}

cheers,

Jayant

3 Likes

This topic was automatically closed after 166 days. New replies are no longer allowed.