在 ol.interaction.Draw 个打开层中捕捉 shift-click 事件

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

我正在尝试使用 ol.interaction.Draw 将多边形添加到 openlayers 地图。我还打开了 Snap 交互,并设置为在按住 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);

这可以禁用捕捉。但是,当我按住 shift 时,我的 Draw 交互不起作用。我知道 condition 参数默认为 ol.events.condition.noModifierKeys,但是当我自定义 condition 时,它甚至都不会被命中!

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

为什么 drawInteraction 会忽略 shift+click 事件?

freehandCondition 的默认设置是捕获 shift+click 事件,因此它们永远不会为 condition 求值。将其更改为其他内容,shift+click 事件将触发您的自定义条件函数。

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