javascriptleafletleaflet-routing-machine

Leaflet routing machine get route summary without drawind route


I am using LRM to calculate routes. And I need data about this routes. Now I'm just learning how to exctract this data so I can use it further. I have two routes

var routing1 =  L.Routing.control({
            waypoints: [
                L.latLng(54.736038, 55.97429),
                L.latLng(54.736985, 55.980878),
            ],
        });

var routing2 =  L.Routing.control({
            waypoints: [
                L.latLng(54.732798, 55.969934),
                L.latLng(54.734954, 55.95809)
            ],
        });

I have a button to draw this routes

document.getElementById("drawing").addEventListener("click", myFunction);
        function myFunction() {
            routing1.addTo(map).on('routesfound', function (e) {
                distance = e.routes[0].summary.totalDistance;
                console.log('routing1 ' + distance);
            });
            routing2.addTo(map).on('routesfound', function (e) {
                distance = e.routes[0].summary.totalDistance;
                console.log('routing2 ' + distance);
            });
        }

As I don't quite understand JS yet so I have this question:


How can I console.log route's summary the moment route calculated? Without drawing it.


Solution

  • TomazicM helped me with solution:


    Upon investigation it turns out that quite a big part of routing process depends on adding L.Routing.control to map. To force route calculation and prevent showing of route on the map requires some hacking trickery:

    Itinerary display must be prevented with show: false option. Endpoints marker display must be prevented by dummy marker creation option createMarker: function(p1,p2) {}. Internal _updateLines method has to be replaced with dummy method. Routing control must be added to map with onAdd(map) method.

    Final code then looks something like this:

    var wayPoint1 = L.latLng(57.74, 11.94);
    var wayPoint2 = L.latLng(57.6792, 11.949);
    
    var bounds = L.latLngBounds(wayPoint1, wayPoint2); 
    
    var myRouting = L.Routing.control({
        waypoints: [wayPoint1, wayPoint2],
        routeWhileDragging: true,
        show: false,
        createMarker: function(p1,p2) {}
    });
    
    myRouting.on('routesfound', function (e) {
        distance = e.routes[0].summary.totalDistance;
        console.log('routing distance: ' + distance);
    });
    
    // save original mathed for later use
    var _updateLines = myRouting._updateLines;
    
    myRouting._updateLines = function (p1) { };
    
    map.fitBounds(bounds);
    myRouting.onAdd(map);