1

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.

Ebizl
  • 19
  • 6

1 Answers1

3

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

kboul
  • 13,836
  • 5
  • 42
  • 53
  • Hi! I don't have access to L.Routing.control, I'm using react-leaflet 3.1, would I need to downgrade ? – Ebizl May 18 '21 at 17:43
  • You need to install the library (`leaflet-routing-machine`) and import it to have access to `L.Routing.control`. It does not have to do with react-leaflet. It is a separate library. You already mentioned it on your question so I thought you were aware of that. – kboul May 18 '21 at 17:52
  • it took me a while, but it seems like lrm is not attaching to L so that I can have access to Routing.control, any thoughts on how to fix this? – Ebizl May 18 '21 at 22:53
  • Take a look at the demo. It has all the necessary code you need to use to run the example. `L.Routing.control` is available if you have installed and imported the library I mentioned earlier. Is this clear? – kboul May 19 '21 at 06:25
  • I have solved the problem I was having in reference to this post https://stackoverflow.com/questions/67552020/how-to-fix-error-failed-to-compile-node-modules-react-leaflet-core-esm-pat I'm now able to run this same example code on my local environment. Thank you @kboul – Ebizl May 22 '21 at 01:22
  • Please accept the answer if it helped you solve your issue – kboul May 22 '21 at 05:53