Using the following code, how do I get the distance of the route directions? I want to run some math against the length.

      container: 'map', // container id
      style: 'mapbox://styles/mapbox/streets-v9',
      center: [-74.50, 40], // starting position
      zoom: 9 // starting zoom
  map.addControl(new mapboxgl.NavigationControl());

  var directions = new MapboxDirections({
    accessToken: mapboxgl.accessToken,

  map.on('load', () => {
    directions.setOrigin([locations[0].longitude, locations[0].latitude]);

  map.addControl(directions, 'bottom-left');```

I think you can get the length of the routes from the following code

// Docs for route event is here:
// https://github.com/mapbox/mapbox-gl-directions/blob/master/API.md#on`enter code here`
directions.on("route", e => {
    // routes is an array of route objects as documented here:
    // https://docs.mapbox.com/api/navigation/#route-object
    let routes = e.route

    // Each route object has a distance property
    console.log("Route lengths", routes.map(r => r.distance))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.