Search code examples
javascriptopenlayers

Deletion of a polygonal selection


I need to highlight selected polygons and then send it to another vector layer. I'm be able to do this with the code below:

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

Problems comes when I draw a new polygon. In that case the previous selection doesn't vanish and the new selection is added to the previous.

enter image description here

In the image above polygons 23840, 23869, 23744 are a part of a selection; 23744, 23897 and 23750 are a part to another selection. Polygon with id 23744 is shared between the two selection.

How I can clean the previous selection when star a draw of a new polygon?


Solution

  • You are adding a new layer to the map for each selected feature. If you have a single source and layer you can clear it before adding more features

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