Search code examples
reactjsleafletreact-leaflet

How should I migrate an existing Leaflet script to upload kml files to run in React-Leaflet


I would like to know how I can migrate the javascript code (plugin) below to run in React. It allows uploading kml files to leaflet running in html but not work in React-Leaflet

https://www.npmjs.com/package/leaflet-filelayer

I'm already using a version of Leaflet for React but it doesn't have an object that allows the upload of kml files on maps...

Thanks for some guidance


Solution

  • Create a custom component where you will load leaflet file layer library after installing and importing it along with togeojson library.

    Therefore install and import the two libraries

    import togeojson from 'togeojson'
    import fileLayer from 'leaflet-filelayer'
    

    call fileLayer(null, L, togeojson) to be able to use L.Control.fileLayerLoad (Source)

    Then create the component as you see it on the official library and place the logic under a useEffect

    ...imports
    
    fileLayer(null, L, togeojson);
    ...
    
    export default function LeafletFileLayer() {
      const map = useMap();
    
      useEffect(() => {
        const control = L.Control.fileLayerLoad({
          fitBounds: true,
          layerOptions: {
            style: style,
            pointToLayer: function (data, latlng) {
              return L.circleMarker(latlng, { style: style });
            }
          }
        });
        control.addTo(map);
        control.loader.on("data:loaded", function (e) {
          var layer = e.layer;
          console.log(layer);
        });
      }, [map]);
    
      return null;
    }
    

    Use it like this

     <MapContainer ...>
        ...
        <LeafletFileLayer />
     </MapContainer>
    

    I uploaded on the sandbox a geojson from the official leaflet site and a kml to be able to test it. You have to download them first.

    Demo