Search code examples
javascriptleafletleaflet-routing-machine

Leaflet Routing Machine - update/redraw route


I'm new about Laflet Routing Machine (liedman) https://www.liedman.net/leaflet-routing-machine/ and I would like to update the first route calculated every 30 seconds because I would like refresh it and I don't need to make many server request.

I'll make a setInterval but at the moment I need to know if it works and if this is the way... this is my code:

routingControl = L.Routing.control({
    waypoints: [
        L.latLng(43.12, 11.99),
        L.latLng(43.37, 12.08)
    ]
    createMarker: function() { return null; },
    routeWhileDragging: false,
    draggableWaypoints: false,
    reverseWaypoints: false,
    fitSelectedRoutes: true,
    addWaypoints: false
}).addTo(OSM_Map);

var newLat = routingControl.options.waypoints[0].lat+0.01;
var newLng = routingControl.options.waypoints[0].lng+0.01;
setTimeout(function () {
   routingControl.options.waypoints=[
       L.latLng(newLat, newLng),
       routingControl.options.waypoints[1]
   ];
}, 10000);

With setTimeout I change the start point (adding 0.01) and checking the waypoints with console.dir they are changed but not the drawn route... how I can refresh it?


Solution

  • The options are only used when initializing the routing control. Changing them afterwards does nothing, since the control uses its own waypoints internally.

    You should be able to use the setWaypoints function like this

    setInterval(function () {
        var newWaypoint = routingControl.getWaypoints()[0].latLng;
        var newLat = newWaypoint.lat + 0.01;
        var newLng = newWaypoint.lng + 0.01;
        routingControl.setWaypoints([
           L.latLng(newLat, newLng),
           routingControl.options.waypoints[1]
         ]);
    }, 10000);
    

    Unlike the options, the getWaypoints always returns the current waypoints, so you can freely modify them. setWaypoints will then trigger a change event for the routes and update them accordingly.

    Here's a working fiddle you can play around with