问题
I want to clear my leaflet map by clicking a button...how to do this... I want to clear all drawed shapes on the map, so the map to be clear
This is my code of the leaflet map in the return statement:
<Map
key={this.state.keyMAP}
style={{ height: "50vh" }}
center={position}
zoom={13}
onClick={this.handleClick}
onCreate={this.onCreate}
onLocationfound={this.handleLocationFound}
>
{/* startDirectly */}
<TileLayer
attribution='© <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:
<button
className="waves-effect waves-light btn"
onClick={this.resetMap}
>
Clear map
</button>
Clear method:
resetMap() {
console.log("Reset");
}
Full code of my component:
https://github.com/SoilViews/SoilViews/blob/master/src/components/dashboard/Dashboard.js
回答1:
I will propose two solutions so that you can choose whichever suits you best. You just need to create DOM references of your map/feature group in React(depends on the chosen method). How to create a reference:
On your constructor, insert the following line:
this.mapRef = React.createRef(); // Create a Map reference
OR
this.fgRef = React.createRef(); // Create a Feature group reference
Then at your <Map>
or <FeatureGroup>
components you should add the following attributes accordingly:
<Map ref={this.mapRef}
key={this.state.keyMAP}
....rest of the code
OR
<FeatureGroup ref={this.fgRef}>
{viewMap && (
....rest of the code
If you choose the map clearing method, you can proceed like this:
function clearMap() { const map = this.mapRef.current.leafletElement; map.eachLayer(function (layer) { map.removeLayer(layer); }); }
Or, if you choose the Feature Group method:
function clearFeatureGroup() { const fg = this.fgRef.current.leafletElement; fg.clearLayers(); }
Finally, in your button you can call the according method:
<button onClick={clearMap}>
Clear!
</button>
OR
<button onClick={clearFeatureGroup}>
Clear!
</button>
来源:https://stackoverflow.com/questions/62166577/how-to-clear-leaflet-map-in-reactjs-by-button