react-leafletmeasurement

react leaflet measurement / ruler plugin


I need a ruler for a React Leaflet app, however, all I can find are the plain leaflet plugins listed at https://leafletjs.com/plugins.html.

I've tried to include all of them in my app but every single one of them has a different compatibility issue with current versions of React and/or Leaflet. Most of these plugins lack proper documentation and many are built for previous versions of leaflet.

Is there a modern measurement plugin or tool that I can use? or is there a well documented procedure to adapt the mentioned plugins to a React-Leaflet environment?


Solution

  • To continue what it was discussed in the comments, you can use leaflet-ruler plugin but without cdns by placing the js and css files locally. I tried using cdns but I got some errors similar to what I would get if I had not imported the library properly.

    Therefore go to https://github.com/gokertanrisever/leaflet-ruler/tree/master/src and copy paste the .css and .js files into two separate files in your React projec (see also the provided demo). Once you do that create a custom react-leaflet component and import the library's css and js file.

    import { useEffect } from "react";
    import { useMap } from "react-leaflet";
    import L from "leaflet";
    import "./leaflet-ruler.css";
    import "./leaflet-ruler";
    
    export default function LeafletRuler() {
      const map = useMap();
    
      useEffect(() => {
        if (!map) return;
    
        L.control.ruler().addTo(map);
      }, [map]);
    
      return null;
    }
    

    Once you do that you are ready to use the library like this:

     <MapContainer center={position} zoom={13} style={{ height: "100vh" }}>
        ...
        <LeafletRuler />
     </MapContainer>
    

    Note that in the sandbox plugin's button image is not displaying properly but in your local environment it should be ok.

    Demo