How to toggle a rectangle grid using react-leaflet's LayerControl?

2k views Asked by At

I want to show or hide a grid of rectangles (the overlay) over a map (the base layer).

I'm using the react Leaflet layers control : doc

Problem : My grid shows all the time even if I uncheck the check box

My grid :

grid picture

class Grid extends MapControl {
    createLeafletElement(props) {
        const { 
          leaflet: { map },
        } = props;

        const minLng = -4.89;  
    const minLat = 41.29;  
    const maxLng = 9.65;   
    const maxLat = 51.22

    const nbColumn = 10;
    const nbRow = 10;
    const rectWidth  = maxLng - minLng;
    const rectHeight = maxLat - minLat;

    const incrLat  = rectHeight  / nbColumn;
    const incrLng = rectWidth / nbRow;
    let column = 0;
    let lngTemp = minLng;
    let latTemp = minLat;

        let rect;
        const arrRect = [];
        while (column < nbColumn) {
          let row = 0;
          latTemp = minLat;
          while (row < nbRow) {
            const cellBounds = [[latTemp, lngTemp], [latTemp + incrLat, lngTemp + incrLng]];
            rect = L.rectangle(cellBounds, {color: "#1EA0AA", weight: 1}).addTo(map);
            arrRect.push(rect);
            latTemp += incrLat; 
            row += 1;
          }
          lngTemp += incrLng;
          column += 1;
        }
        return rect;
    }
}

In my leaflet component :

class Leaflet extends Component {
   ...
render() {
  return (
      <Map 
         <LayersControl>
            <LayersControl.BaseLayer name="Open Street Map" checked="true">
                <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> 
                           contributors'
                           url={this.state.url}
                 />
            </LayersControl.BaseLayer>

            <LayersControl.Overlay name="Grid1">
               <LayerGroup>
                  <Grid />     
              </LayerGroup>
            </LayersControl.Overlay>
      </LayersControl>
1

There are 1 answers

5
kboul On BEST ANSWER

I did not manage to load your grid so I provide another simpler grid example.

To control the Grid's visibility you need to use react-leaflet's updateLeafletElement method to trigger prop changes on your custom react-leaflet component. Pass a showGrid prop to be able to control Grid's visibility.

updateLeafletElement(fromProps, toProps) {
    const { map } = this.props.leaflet;
    if (toProps.showGrid !== fromProps.showGrid) {
      toProps.showGrid
        ? this.leafletElement.addTo(map)
        : this.leafletElement.removeFrom(map);
    }
  }

then in your map component listen to leaflet's overlayadd & overlayremove to be able to toggle a local flag which will control the visibility of the grid using an effect:

useEffect(() => {
    const map = mapRef.current.leafletElement;
    map.on("overlayadd", (e) => {
      if (e.name === "Grid1") setShowGrid(true);
    });

    map.on("overlayremove", (e) => {
      if (e.name === "Grid1") setShowGrid(false);
    });
  }, []);


  <LayersControl.Overlay
          checked={showGrid}
          name="Grid1"
        >
          <LayerGroup>
            <Grid showGrid={showGrid} />
          </LayerGroup>
  </LayersControl.Overlay>

Edit: The App component as class based component it will look like this:

export default class AppWithNoHooks extends Component {
  state = {
    showGrid: false
  };

  mapRef = createRef();

  componentDidMount() {
    const map = this.mapRef.current.leafletElement;
    map.on("overlayadd", (e) => {
      if (e.name === "Grid1") this.setState({ showGrid: true });
    });

    map.on("overlayremove", (e) => {
      if (e.name === "Grid1") this.setState({ showGrid: false });
    });
  }
 ...

I don't get the error you mentioned.

Demo