perliedman / leaflet-routing-machine

Control for routing in Leaflet
https://www.liedman.net/leaflet-routing-machine/
Other
1.06k stars 347 forks source link

update/redraw a drawn route #647

Open FranGhe opened 2 years ago

FranGhe commented 2 years ago

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?

curtisy1 commented 2 years ago

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

FranGhe commented 2 years ago

Thanks so much for your support... if you want you can reply also here: https://stackoverflow.com/questions/70627857/leaflet-routing-machine-update-redraw-route

Thanks again!