[GIS] Reset leaflet routing machine route and controls

leaflet

Im trying to build a geolocation based routing app in angular using leaflet.js and leaflet routing machine. I have this 'addRouting' function where I pass in a users location (fromLat, fromLng) and also a destination (toLat, toLng).

I am able to get an initial route to display but I am having some trouble clearing the map and controls so that I can pass in a new route and direction. With this current code the second route does not draw and I get a completely new set of controls displaying as seen below.

enter image description here

I think I need some way to clear and reset the map and routing functionality. Im new to using both leaflet and leaflet routing machine and I'm struggling to understand how this can be done.

  // Add Routing
  $scope.addRouting = function (fromLat, fromLng, toLat, toLng) {

    // Get map object
    leafletData.getMap().then(function(map) {

      // fit map
      map.fitBounds([[fromLat, fromLng], [toLat, toLng]]);

      // clear route and controls


      // add new routing
      L.Routing.control({
        waypoints: [
            L.latLng(fromLat, fromLng),
            L.latLng(toLat, toLng)
        ]
      }).addTo(map);

    });
  }

Best Answer

If you keep a reference to the L.Routing.Control around you can remove it later on.

$scope.routingControl =  L.Routing.control({
    waypoints: [
        L.latLng(fromLat, fromLng),
        L.latLng(toLat, toLng)
    ]
  }).addTo(map);

and to remove it:

$scope.removeRouting = function() {
    leafletData.getMap().then(function(map) {
        map.removeControl($scope.routingControl);
    });
};

Or if your just aiming to change the routing waypoints theres no need to remove it and create a new routing control, you can just change the waypoints:

$scope.updateRoute = function (fromLat, fromLng, toLat, toLng) {
    $scope.routingControl.getPlan().setWaypoints([
        L.latLng(fromLat, fromLng),
        L.latLng(toLat, toLng)
    ]);
};
Related Question