javascriptleafletleaflet-routing-machine

How can I get the distance and time from L.Routing.control?


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);

Solution

  • 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