Search code examples
javascriptopenlayers

catch shift-click events in ol.interaction.Draw Open Layers


I'm trying to use ol.interaction.Draw to add polygons to an openlayers map. I also have a Snap interaction on, and set up to turn off while I'm holding down shift.

const
  snapInteraction = new ol.interaction.Snap({
    source: drawLayer.getSource()
  }),
  turnOnSnap = (evt) => {
    if (!isShiftKey(evt)) {
      return;
    }
    console.log('shift key is down, turning off snap');
    snapInteraction.setActive(false);
  },
  turnOffSnap = (evt) => {
    if (!isShiftKey(evt)) {
      return;
    }
    console.log('shift key is up, turning on snap');
    snapInteraction.setActive(true);
  };

document.addEventListener('keydown', turnOnSnap);
document.addEventListener('keyup', turnOffSnap);

This works to disable snapping. However, my Draw interaction doesn't work when I hold down shift. I know that the condition parameter defaults to ol.events.condition.noModifierKeys, but when I make a custom condition it never even gets hit!

const drawInteraction = new ol.interaction.Draw({
  source: drawLayer.getSource(),
  type: 'Polygon',
  condition: function (evt) {
    console.log("yo, why isn't this hit when I hold down shift?", evt);
    return (ol.events.condition.noModifierKeys(evt) ||
      ol.events.condition.shiftKeyOnly(evt));
  }
});

Why is the drawInteraction ignoring the shift+click events?


Solution

  • The default for freehandCondition is catching shift+click events, so they never get evaluated for condition. Change that to something else, and the shift+click events will hit your custom condition function.

    const drawInteraction = new ol.interaction.Draw({
      source: drawLayer.getSource(),
      type: 'Polygon',
      condition: function (evt) {
        return (ol.events.condition.noModifierKeys(evt) ||
          ol.events.condition.shiftKeyOnly(evt));
      },
      freehandCondition: ol.events.condition.never, // <-- add this line
    });