2

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);

    });
  }
  • To clarify, Routing in Angular and Routing in Leaflet may mean two different things. Could you please clear up what, exactly, you mean by "routing"? – standers Jun 23 '15 at 20:48
  • @standers I meant routing in 'leaflet routing machine' i.e wayfinding on a leaflet map not url routing in angular. – lukus Jun 24 '15 at 8:45
3

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)
    ]);
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.