Leaflet. js Как удалить выбранный слой на карте, когда карта отображается с нарисованными элементами - PullRequest
1 голос
/ 21 января 2020

Я пытался отображать поверхности в форме многоугольника на карте каждый раз, когда пользователь нажимает на слой формы многоугольника. Отображается всплывающее окно с деталями многоугольника, и слой можно редактировать. Во всплывающем окне есть возможность удалить многоугольник. После нажатия кнопки «Удалить» во всплывающем окне я попытался повторно инициализировать карту с новыми поверхностями, т.е. данными (полигонами), но выбранная поверхность все равно появляется.

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 });
   });
 }

1 Ответ

2 голосов
/ 22 января 2020

. Во всплывающем окне есть возможность удалить многоугольник.

Пожалуйста, проверьте приведенный ниже пример.

// 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>

Надеюсь, это поможет вам

...