Poul K. Sørensen Poul K. Sørensen - 2 months ago 35
Javascript Question

Remove last point from Draw Interaction in Ol3

I am trying to remove the last point in a polygon draw feature on esc key.

The following code do not work. It seems to remove it when it draw the area part, but the vertex is stil there.

var geom :ol.geom.Polygon = null;
draw.on("drawstart",(event) => {
console.log(event);
var feature :ol.Feature= event.feature;
console.log(feature);
geom = feature.getGeometry<ol.geom.Polygon>();
});

$(document).keyup((e)=> {
if (e.keyCode === 27) {
var coords = geom.getCoordinates()[0];
if(coords.length>1)
geom.setCoordinates([coords.slice(0, coords.length - 2)]);
}
});

Answer

You need to use a setCoordinates on the geometry element, after removing the last segment.

Here is an example:

this.olDraw.on('drawstart',
  function (evt) {
    $(document).on('keyup', function (event) {
      if (event.keyCode === 27) {
        var feature = evt.feature;
        var geom = feature.getGeometry();
        if (geom.getType() === LINE_STRING) {
          geom.setCoordinates(geom.getCoordinates().slice(0,geom.getCoordinates().length - 1));
        }
      }
    });
  }, this);
Comments