简体   繁体   中英

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

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 :

网格图片

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM