Search code examples
javascriptopenlayerspolygon

How do I limit the number of polygons in a layer?


My code currently allows the user to have the ability to create many polygons at once. I would like it to instead erase the previous vector everytime the user decides to create a new one.

let drawSource = new VectorSource({wrapX: false}); 

let drawLayer = new VectorLayer({source : drawSource,})
this.map.addLayer(drawLayer);

let draw = new Draw({
  source : drawSource,
  type : GeometryType.POLYGON,
  style : new Style({
    stroke: new Stroke({
          color: "#f00",
          width: 1,
        }),
    fill: new Fill({
      color: "#300",
    })
  })
});
this.map.addInteraction(draw)

Solution

  • Clear the source when a new drawing is started

    draw.on('drawstart', function() {
      drawSource.clear();
    });