Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React-leaflet #82

Open
pilotto360 opened this issue Nov 30, 2021 · 1 comment
Open

React-leaflet #82

pilotto360 opened this issue Nov 30, 2021 · 1 comment

Comments

@pilotto360
Copy link

I would like to know how to install leaflet-filelayer in React (React-leaflet)....

@dtrucs
Copy link
Member

dtrucs commented Nov 29, 2024

Below i paste a way to handle it:

FileLayerControl.js

import { useEffect } from 'react';
import { useMap } from 'react-leaflet';

import * as L from 'leaflet';
import * as ToGeojson from 'togeojson';
import * as FileLayer from 'leaflet-filelayer';

const FileLayerControl = () => {
  const map = useMap();

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

    FileLayer(null, L, ToGeojson);

    const fileLayerControl = L.Control.fileLayerLoad({
      // Allows you to use a customized version of L.geoJson.
      // For example if you are using the Proj4Leaflet leaflet plugin,
      // you can pass L.Proj.geoJson and load the files into the
      // L.Proj.GeoJson instead of the L.geoJson.
      layer: L.geoJson,
      // See http://leafletjs.com/reference.html#geojson-options
      layerOptions: { style: { color: 'red' } },
      // Add to map after loading (default: true) ?
      addToMap: true,
      // File size limit in kb (default: 1024) ?
      fileSizeLimit: 5000,
      // Restrict accepted file formats (default: .geojson, .json, .kml, and .gpx) ?
      formats: ['.geojson', '.kml'],
    }).addTo(map);

    fileLayerControl.loader.on('data:loaded', event => {
      console.log(event);
    });

    fileLayerControl.loader.on('data:error', error => {
      // Do something useful with the error!
      console.error(error);
    });

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

  return null;
};

export default FileLayerControl;

And Map.js

import { MapContainer } from 'react-leaflet';
import FileLayerControl from '@/components/FilelayerControl';


const Map = () => {
  const position = [51.505, -0.09]
  return (
    <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
       <FileLayerControl />
    </MapContainer>
  );
};

export default Map;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants