-->

MKMapView get distance between coordinates on cust

2019-09-01 07:18发布

问题:

I have a custom route on map and want to get the distance between two coordinates on MKMapView. Below are the steps I have done so far...

  1. I have grabbed coordinate points and prepared an array of CLLocationCoordinate2D (like, customRoute = [CLLocationCoordinate2D]).
  2. To show the route, using array of coordinates, I have drawn MKPolyline using MKOverlay method.
  3. And calculating the distance between two coordinates using distanceFromLocation method.

When I calculate distance, the resulting distance is a straight line distance but not based on directions.

Lets say a user is at location A (on custom route) and wants to reach location B (on custom route). So all I want to calculate is the distance between A and B (not straight line distance).

Right now I'm finding out the nearest coordinate from the user location and calculating the distance to the destination by looping through the array of coordinates. But this doesn't give the proper result when there are multiple routes and the nearest point is on the other route.

One thing struck my mind was to set the custom directions on map and find the distance, but I've no idea on how to achieve this.

Language being used is Swift.

Any kind of help/suggestion is much appreciated.

回答1:

According to the docs on distanceInMeters:

This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth. The resulting arc is a smooth curve and does not take into account specific altitude changes between the two locations.

So the method in fact returns a "straight line."

As far as I know, you'll need to create individual MKRoute objects between each section of your custom route, calculate those individual distances, then combine them.

As I've explained in this answer, you can calculate each individual MKRoute's distance by fetching the MKDirectionsResponse like so:

let request:MKDirectionsRequest = MKDirectionsRequest()

// source and destination are the relevant MKMapItems
request.setSource(source)
request.setDestination(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)

directions.calculateDirectionsWithCompletionHandler ({
    (response: MKDirectionsResponse?, error: NSError?) in

    if error == nil {
        self.directionsResponse = response
    }
})

then getting the distance like so:

let route = directionsResponse.routes[currentRoute] as MKRoute
let distance = route.distance