L.Routing.control on react-leaflet v3 with hooks

Viewed 1165

I only see that L.Routing.control works with under version 3, is there an equivalent version to it on v3? I'm trying to set up waypoint routing and directions between two points.

1 Answers

You can create your own custom component to set up routing between two points using leaflet-routing-machine:

Install the library:

npm i leaflet-routing-machine

Import library's css file:

import "leaflet-routing-machine/dist/leaflet-routing-machine.css";

Import library's js file:

import "leaflet-routing-machine";

Create the custom comp:

function Routing() {
  const map = useMap();

  useEffect(() => {
    if (!map) return;

    const routingControl = L.Routing.control({
      waypoints: [L.latLng(57.74, 11.94), L.latLng(57.6792, 11.949)],
      routeWhileDragging: true
    }).addTo(map);

    return () => map.removeControl(routingControl);
  }, [map]);

  return null;
}

then use it as a regular react-leaflet component:

<MapContainer ...>
  ...
  <Routing/>
</MapContainer>

Demo

Related