4

I am drawing a route on a leaflet map, it works good and in the control it shows the distance and estimated time of arrival. Is there a way to extract both of them and save them?

The code for the L.Routing.control

function getroute() {
myroutewithout = L.Routing.control({
  waypoints: [
    L.latLng(window.my_lat, window.my_lng),
    L.latLng(window.job_p_lat, window.job_p_lng)
  ],show: true, units: 'imperial',
 router: L.Routing.mapbox('API-KEY-HERE'),
  createMarker: function(i, wp, nWps) {
    if (i === 0 || i === nWps + 1) {
      // here change the starting and ending icons
      return mymarker = L.marker(wp.latLng, {
        icon: operatoricon
      });
    } else {
      return job_start = L.marker(wp.latLng, {
        icon: jobicon
      }); 
    }
  }
}).addTo(map);
kboul
  • 13,836
  • 5
  • 42
  • 53
larry chambers
  • 473
  • 1
  • 6
  • 19
  • 1
    What do you mean "save" them - store in a variable to use elsewhere? What plugin are you using for routing? – chazsolo Dec 31 '18 at 15:14
  • 1
    Im using leaflet-routing-machine, and just for instance just alert them. – larry chambers Dec 31 '18 at 15:18
  • 1
    I don't see a straightforward way to expose that data, but the [docs for the Router](http://www.liedman.net/leaflet-routing-machine/api/#irouter) suggest that you can provide a callback that has an array of routes - each route contains an array of instructions, which include distance and time. You might be able to iterate over that? – chazsolo Dec 31 '18 at 15:30

1 Answers1

8

You can achieve that using the code from this issue

var routeControl = L.Routing.control({...});
...
routeControl.on('routesfound', function(e) {
   var routes = e.routes;
   var summary = routes[0].summary;
   // alert distance and time in km and minutes
   alert('Total distance is ' + summary.totalDistance / 1000 + ' km and total time is ' + Math.round(summary.totalTime % 3600 / 60) + ' minutes');
});

Demo

kboul
  • 13,836
  • 5
  • 42
  • 53