How to remove the previous route from leaflet.js

79 Views Asked by At

Currently everytime when I click in one markers it shows the route from the current location to the marker clicked.

I want that when I click in another marker the previous route disappear and shows only the new route.

This is how the UI is behaving right now. I have 2 routes.

UI showing 2 routes

I tried to do something like this but I keep getting 2 routes.


import { useEffect, useRef } from "react";
import L from "leaflet";
import "leaflet-routing-machine";

function RoutingMachine({ currentLocation, selectedTerritory }) {
  const map = useMap();
  const routingControlRef = useRef(null);
  const currentRouteRef = useRef(null); // Reference to the current route

  useEffect(() => {
    if (!map) return; // Wait for the map to be ready

    if (!routingControlRef.current) {
      // Create the routing control only once
      const newRoutingControl = L.Routing.control({
        waypoints: [],
        lineOptions: {
          styles: [{ color: "#BC8F8F", weight: 4 }]
        },
        routeWhileDragging: true,
        plan: L.Routing.plan([], {
          show: true
        })
      });

      newRoutingControl.addTo(map);
      routingControlRef.current = newRoutingControl;
    }

    // Update the waypoints and remove the previous route when currentLocation or selectedTerritory changes
    if (currentLocation && selectedTerritory) {
      const waypoints = [
        L.latLng(currentLocation[0], currentLocation[1]),
        L.latLng(selectedTerritory.latLong[0], selectedTerritory.latLong[1])
      ];

      // Remove the previous route from the map if it exists
      if (currentRouteRef.current) {
        map.removeLayer(currentRouteRef.current);
      }

      // Set the new waypoints and store the new route reference
      const newRoute = routingControlRef.current.setWaypoints(waypoints);
      currentRouteRef.current = newRoute;
    }
  }, [map, currentLocation, selectedTerritory]);

  return null;
}
0

There are 0 best solutions below