4
votes

I'm using MapBox GL API for Qt (JavaScript), and I have to get the total distance and total duration from a route. To obtain the route, I'm making the following http request:

https://api.mapbox.com/directions/v5/mapbox/driving/-8.61767353533753,42.102184359031504;-8.495246688170312,41.44289308091726?steps=true&geometries=geojson&access_token=myToken

The response is in geoJSON format, which I use to draw the route on my map, and it works.

The problem is I can't calculate the total distance and duration of the whole trip. There are many "duration" and "distance" fields in this geoJSON.

Do I have to work with these multiple fields, or is there any other way to calculate the total distance and duration?

2
Just as tip, you are sharing here the API url but this contains your access token too. - leonardfactory
@leonardfactory Thanks for the tip! I solved my problem following the Steve Bennett indications. Thank you too for your help! - HMI SW

2 Answers

3
votes

To get the distance and duration, just take routes[0].distance and routes[0].duration respectively.

(You don't want to add them up: these represent alternative routes, not parts of one long journey.)

See https://docs.mapbox.com/api/navigation/#directions-response-object .

1
votes

You can use the turf.js library passing it the geoJSON and then do some spacial analysis.

The concept here is to pass a geoJSON feature to turf and use the length function:

var geojson = /** get your shape from API */;
var length = turf.length(geojson, {units: 'kilometers'});

Here is an example directly from MapBox: https://docs.mapbox.com/mapbox-gl-js/example/measure/

Edit: since there is a duration and distance in the routes specified by mapbox api, you can process the geojson.routes object, like this:

var duration = geojson.routes.reduce(
 (d, route) => d + route.duration
 0
);

This way you can even use the route.distance field in order the get the total distance.

EDIT n.2: DON'T DO THIS! I messed it up, routes is just an array of alternatives, kudos to Steve Bennet for pointing this out.