vietstone
vietstone

Reputation: 9092

iOS: distance of route between two locations (route, not straight line)

I have a MKMapview with multiple annotations. When the user chooses an annotation, the "callout" view shows the location's name and the distance between the location and the user location.

I'm stuck at getting the distance. Prior to iOS 5, I could use Google direction API to get the distance, but now I can't. Is there any alternative solution?

Thank you!

EDIT:

The distance I refer is the distance of the route between two locations. The route has many routes. It's not the distance of the straight line as the result of "distanceFromLocation:"

Upvotes: 0

Views: 3161

Answers (2)

vietstone
vietstone

Reputation: 9092

Now (iOS 7 and later) you can get a route with MKDirections, MKDirectionsRequest and MKDirectionsResponse.

The route information is MKRoute (there's a distance property).

For an example follow this link.

Upvotes: 2

eric.mitchell
eric.mitchell

Reputation: 8855

If you have two CLLocations, you can use the distanceFromLocation: method to get the distance in meters between them.

Example:

CLLocation* first = [[CLLocation alloc] initWithLatitude:firstLatitude longitude:firstLongitude];
CLLocation* second = [[CLLocation alloc] initWithLatitude:secondLatitude longitude:secondLongitude];

CGFloat distance = [first distanceFromLocation:second];

You can get the latitude and longitude of your annotation (not your annotation view) from its coordinate or similar property on your annotation class.

If you have a list of annotations and want to get the distance of a path between them, simply:

CGFloat distance = 0;
for(int idx = 0; idx < [mapView.annotations count] - 1; ++idx) {
    CLLocationCoordinate2D firstCoord = [mapView.annotations[idx] coordinate];
    CLLocationCoordinate2D secondCoord = [mapView.annotations[idx + 1] coordinate];

    CLLocation* first = [[CLLocation alloc] initWithLatitude:firstCoord.latitude longitude:secondCoord.latitude];
    CLLocation* second = [[CLLocation alloc] initWithLatitude:secondCoord.latitude longitude:secondCoord.longitude];

    distance += [first distanceFromLocation:second];
}

Upvotes: 4

Related Questions