目前,每次我单击一个标记时,它都会显示从当前位置到单击的标记的路线。
我希望当我单击另一个标记时,之前的路线消失并仅显示新路线。
这就是 UI 现在的行为方式。我有2条路线。
我尝试做这样的事情,但我不断得到 2 条路线。
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;
}