Ebizl
Ebizl

Reputation: 19

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

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.

Upvotes: 1

Views: 3215

Answers (1)

kboul
kboul

Reputation: 14600

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

Upvotes: 3

Related Questions