删除多边形选择

Deletion of a polygonal selection

我需要突出显示选定的多边形,然后将其发送到另一个矢量图层。我可以使用以下代码执行此操作:

  const ghostDataLayer = new ol.layer.Vector(....
  let drawingSource = new ol.source.Vector({useSpatialIndex: false});

  let draw;

  draw = new ol.interaction.Draw({
    type: 'Polygon',
    source: drawingSource,
    style: style
  });
  map.addInteraction(draw);


  function highlightSelection(drawnPolygon) {
      ghostDataLayer.getSource().forEachFeatureIntersectingExtent(drawnPolygon, function(feature) {

          selectedFeatureCoordinates = feature.getGeometry().getCoordinates();

          const selectedGeometry = new ol.geom.MultiPolygon(selectedFeatureCoordinates);
          const selectedPolygonFeature = new ol.Feature({
            geometry: selectedGeometry
          });
          const selectedSource = new ol.source.Vector({
            features: [selectedPolygonFeature]
          });
          const selectedLayer = new ol.layer.Vector({
            source: selectedSource,
            style: selectedPolygonStyle,
            zIndex: 99,
          });
          map.addLayer(selectedLayer);

      });
  };


  draw.on('drawstart', function(event){
    drawingSource.clear();
  }, this);

  draw.on('drawend', function(event) {
    let drawnPolygonExtent = event.feature.getGeometry().getExtent();
    highlightSelection(drawnPolygonExtent);
  });

绘制新多边形时出现问题。在这种情况下,先前的选择不会消失,新的选择会添加到先前的选择中。

上图中多边形23840、23869、23744是选区的一部分; 23744、23897 和 23750 是另一个选择的一部分。 id 为 23744 的多边形在两个选择之间共享。

在绘制新多边形时如何清除之前的选择?

您正在为每个选定的要素向地图添加一个新图层。如果您只有一个来源和图层,您可以在添加更多功能之前将其清除

  const selectedSource = new ol.source.Vector();
  const selectedLayer = new ol.layer.Vector({
    source: selectedSource,
    style: selectedPolygonStyle,
    zIndex: 99,
  });
  map.addLayer(selectedLayer);

  function highlightSelection(drawnPolygon) {
      selectedSource.clear();
      ghostDataLayer.getSource().forEachFeatureIntersectingExtent(drawnPolygon, function(feature) {

          selectedFeatureCoordinates = feature.getGeometry().getCoordinates();

          const selectedGeometry = new ol.geom.MultiPolygon(selectedFeatureCoordinates);
          const selectedPolygonFeature = new ol.Feature({
            geometry: selectedGeometry
          });
          selectedSource.addFeature(selectedPolygonFeature);

      });

  };