1

I am using Leaflet 1.2.0 and Leaflet Routing Machine 3.2.12.

My code is drawing the correct route on the map, yet, when i want to access the summary and the totalDistance from the summary, both are undefined. Why is that?

function createRoute(id, coords) {
            route = L.Routing.control({
                    name: id,
                    serviceUrl: 'http://router.project-osrm.org/route/v1',
                    //router: L.Routing.graphHopper('apiKey');
                    waypoints: coords, //way_points,
                    addWaypoints: false,
                    draggableWaypoints: false,
                    show: false,
                }).on('routesfound', function(e) {
                    console.log(this.summary.totalDistance);
                    // console.log(route.summary.totalDistance);
                     
                })
                    //.on('routesfound', function(e) {
                    //    routes = e.routes;  //is declared and instantiated before the function 
                    //                        // createRoute
                    //    RouteLength = routes[0].summary.totalDistance;
                    //});
                .addTo(map);
    }

The error: Routing Error: status -3 TypeError: Cannot read properties of undefined (reading 'totalDistance').

From the console i get the escalation of:

fire    @   leaflet.js:5
(anonym)    @   leaflet-routing-machine.js:16166
(anonym)    @   leaflet-routing-machine.js:18004
loaded  @   leaflet-routing-machine.js:46
load (asynchron)        
corslite    @   leaflet-routing-machine.js:53
route   @   leaflet-routing-machine.js:17977
route   @   leaflet-routing-machine.js:16151
onAdd   @   leaflet-routing-machine.js:15919
addTo   @   leaflet.js:5
createRoute @   POI-Dash implement Routing.html:586

Anyone know more about it?

marian
  • 27
  • 7

1 Answers1

0

this doesn't have a summary. You will need to refer to e.routes, like e.routes[0].summary.totalDistance.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • That solved it... I'm not quite sure why I wouldn't be able to access it this way after the `addTo(map);` I tried to console.log(route) and it worked and thats where i noticed there's totalDistance value in there but trying to console.log(route.summary.totalDistance) would always return with summary and totalDistance undefined. – marian Dec 03 '21 at 20:19
  • @marian you can access the route variable in the callback function, but the reason you cannot access the routes in the way you intended is that 1. The routes can be accessed through the event variable (`e`) and 2. At the `routesfound` event you have the possibility to have more routes, so it is logical that this kind of plurality has to be supported instead of assuming that there is a single route. If my answer helped you solve the problem, then you might consider accepting it as the correct answer. – Lajos Arpad Dec 04 '21 at 16:04