Leaflet.js使用Drawn Items重新渲染地图时,如何移除地图中的选定图层

Leaflet.js How to remove the selected layer in Map when map is re rendered with Drawn Items

每当用户点击多边形形状图层弹出窗口时,我都尝试在地图上渲染多边形表面 显示多边形详细信息,层可以是 edited.In 弹出窗口,有删除多边形的选项。在弹出窗口中单击“删除”后,我尝试使用新表面(即(多边形)数据)重新初始化地图,但仍然会出现所选表面。

componentDidUpdate(prevProps, prevState) {
   const { user, surfaces } = this.props;
   const { allLayers } = this.state;
   const that = this;
   let selectedSurface = null;
   if (!prevProps.user.id && user.id) {
     this.initializeMap();
   }
   if (this.props.deleteAction.success !== prevProps.deleteAction.success) {
     this.props.actionFetch();
     map.remove();
     this.initializeMap();
   }
   if ((allLayers.length === 1 && surfaces.length) || (surfaces.length !== 
      prevProps.surfaces.length)) {
     let allLayers = [{ key: -1, name: this.props.intl.formatMessage({ id: 
     'surface.allsurfaces' }), color: '#CCCCCC' }];
      surfaces.forEach((o) => {
        let l = L.geoJSON(o.geometry)._layers;
        [l] = Object.keys(l).map(ob => l[ob]);
        const customlayer = this.addPopupToLayer(o, l);
        map.addLayer(drawnItems[o.surface_type.id].addLayer(customlayer));
         l.on('click', (e) => {
          if (selectedSurface) {
          selectedSurface.editing.disable();
         }
        selectedSurface = e.target;
        e.target.editing.enable();
          that.setState({
            popup: true,
            detail: true,
            surfaceDetail: o,
            typeSelected: o.surface_type,
            editSurface: selectedSurface
          });
        });

     allLayers.push({
       key: o.surface_type.id,
       name: o.surface_type.name,
       color: o.surface_type.color
     });
   });
   allLayers = allLayers.filter(
     (l, index, self) => self.findIndex(
       t => t.key === l.key
       ) === index
     );
     this.setState({
      allLayers,
      counter: surfaces.length
    });
  }
 }

initializeMap() {
  const { user, actionFetch, actionFetchTypes } = this.props;
  actionFetch();
  actionFetchTypes();
   map = L.map('map', {
    center: [...user.airport.location.coordinates].reverse(),
    zoom: 15,
    editable: true,
   });
   L.gridLayer.googleMutant({ type: 'satellite', maxZoom: 20 }).addTo(map);

    const that = this;
    map.on(L.Draw.Event.CREATED, (e) => {
     drawnItems[that.state.typeSelected.key].addLayer(e.layer);
     utils.toggleZooming(map, 'disable');
    that.setState({ popup: true, layer: e.layer });
    });
    map.on('draw:deleted', (e) => {
      that.setState({ popup: false });
   });
 }

.In the popup, there is option to delete the polygon.

请检查下面的示例。

// initialize the map
var map = L.map('map', {
  center: [0.4, 102],
  zoom: 7
});

// add map layer (OpenStreetMap)
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
}).addTo(map);

// load example GEOJSON (from Wikipedia)
var geojsonFeature = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [102.0, 0.5]
      },
      "properties": {
        "prop0": "A"
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
        ]
      },
      "properties": {
        "prop0": "B",
        "prop1": 0.0
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
        ]
      },
      "properties": {
        "prop0": "C",
        "prop1": {"this": "that"}
      }
    }
  ]
};


// load GEOJSON object/array to map
L.geoJSON(geojsonFeature, {
  // style features based on properties
  style: function(feature) {
    switch(feature.properties.prop0){
      case 'B': return { color: "red" }
      case 'C': return { color: "green" }
    }
  },
  // replace default maker with circle for point feature
  pointToLayer: function(feature, latlng) {
    return L.circleMarker(latlng, {
      radius: 14,
      fillColor: "orange",
      color: "orange",
      weight: 2,
      opacity: 1,
      fillOpacity: 0.5
    });
  },
  // bind tooltip to each feature
  onEachFeature: function(feature, layer) {
  
  var popupContent = "<button onclick='removeSelectedLayer(\""+feature.properties.prop0+"\")'>Click here to remove this polygon</button><p>";

  if (feature.properties.prop0) {
   popupContent += feature.properties.prop0;
  }

  layer.bindPopup(popupContent);
    layer.myTag  = feature.properties.prop0
    }
}).addTo(map);


function removeSelectedLayer(layerName) {
  
        map.eachLayer( function(layer) {
console.log(layer.myTag)
          if ( layer.myTag  &&  layer.myTag === layerName) {
            map.removeLayer(layer)
              }

            });

    }
#map {
  height: 500px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"crossorigin=""></script>

<div id="map"></div>

希望对您有所帮助