如何通过按钮清除reactjs中的传单图?

问题描述 投票:0回答:1

我想通过单击按钮来清除我的传单地图...如何执行此操作...我想清除地图上所有绘制的形状,因此要清除地图

这是我在return语句中的单张地图代码:

 <Map
            key={this.state.keyMAP}
            style={{ height: "50vh" }}
            center={position}
            zoom={13}
            onClick={this.handleClick}
            onCreate={this.onCreate}
            onLocationfound={this.handleLocationFound}
          >
            {/* startDirectly */}

            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
              layers="NDVI"
              // baseUrl="https://services.sentinel-hub.com/ogc/wms/bb1c8a2f-5b11-42bb-8ce4-dbf7f5300663"
            />

            <FeatureGroup>
              {viewMap && (
                <EditControl
                  position="topleft"
                  onEdited={this._onEditPath}
                  onCreated={this.onCreate}
                  onDeleted={this._onDeleted}
                  onMounted={this._mounted}
                  onEditStart={this._onEditStart}
                  onEditStop={this._onEditStop}
                  onDeleteStart={this._onDeleteStart}
                  onDeleteStop={this._onDeleteStop}
                  draw={{
                    rectangle: false,
                    marker: false,
                    circleMarker: false,
                    circle: false,
                    circlemarker: false,
                  }}
                />
              )}
            </FeatureGroup>
          </Map>

按钮:

 <button
            className="waves-effect waves-light btn"
            onClick={this.resetMap}
          >
            Clear map
          </button>

清除方法:

resetMap() {
    console.log("Reset");
  }

我的组件的完整代码:

https://github.com/SoilViews/SoilViews/blob/master/src/components/dashboard/Dashboard.js

reactjs react-leaflet leaflet.draw
1个回答
0
投票

我将提出两个解决方案,以便您可以选择最适合您的一个。您只需要在React中创建地图/功能组的DOM引用(取决于所选方法)。如何创建参考:

在构造函数上,插入以下行:

 this.mapRef = React.createRef(); // Create a Map reference

OR

 this.fgRef = React.createRef(); // Create a Feature group reference

然后在<Map><FeatureGroup>组件上,应相应添加以下属性:

<Map ref={this.mapRef} key={this.state.keyMAP} ....rest of the code

OR

<FeatureGroup ref={this.fgRef}> {viewMap && ( ....rest of the code

  1. 如果选择地图清除方法,则可以这样进行:

    function clearMap() {
      const map = this.mapRef.current.leafletElement;
      map.eachLayer(function (layer) {
        map.removeLayer(layer);
      });
    }
    
  2. 或者,如果您选择要素组方法:

    function clearFeatureGroup() {
        const fg = this.fgRef.current.leafletElement;
        fg.clearLayers();
     }
    

最后,您可以在按钮中调用相应的方法:

<button onClick={clearMap}>
   Clear!
</button>

OR

<button onClick={clearFeatureGroup}>
   Clear!
</button>
© www.soinside.com 2019 - 2024. All rights reserved.