Undoing last point when drawing linestring in OpenLayers 3?

Since OpenLayers 3.9.0, this is as simple as using the removeLastPoint method of the DrawInteraction. So you can do something like this:

document.addEventListener('keydown', function(e) {
    if (e.which == 27)
        draw_interaction.removeLastPoint()
});

Since v3.6.0, a geometryFunction is used to return the geometry resulting from drawing with ol.interaction.Draw. This geometryFunction is where you modify the geometry during drawing. So what you can do is set an undo flag to true when the user hits the Esc key. In the geometryFunction you change the coordinates when the flag was set:

var undo = false; // set this to true in the Esc key handler
var draw = new ol.interaction.Draw({
  // ...
  geometryFunction: function(coords, geom) {
    if (!geom) {
      geom = new ol.geom.LineString(null);
    }
    if (undo) {
      if (coords.length > 1) {
        coords.pop();
      }
      undo = false;
    }
    geom.setCoordinates(coords);
    return geom;
  }
});

Tags:

Openlayers