首页 > 解决方案 > 如何在 Openlayers 4 中的 ol.control 上添加点击事件监听器?

问题描述

我正在尝试记录 UI 交互,因此我想从我的ol.controls( ol.control.Zoom, ol.control.Rotate, ol.control.Attribution) 获取点击/标签事件。

但是怎么做?我在文档中找不到任何内容

标签: angularopenlayers

解决方案


我当时也没有找到,但我也可能错过了重点。您可能会忘记使用 OpenLayers API,而使用纯 JavaScript。

// Check zoom +/- buttons event
document.querySelector('.ol-zoom').addEventListener('click', evt => {
  if (evt.target.classList.contains('ol-zoom-in')) {
    console.log('Zoom in');
  } else if (evt.target.classList.contains('ol-zoom-out')) {
    console.log('Zoom out');
  }
});

// Check if rotate button clicked (normally visible only if map rotated)
document.querySelector('.ol-rotate').addEventListener('click', evt => {
  console.log('Rotate');
});

// Check if attribution button opened or closed
document.querySelector('.ol-attribution').addEventListener('click', evt => {
  if (evt.currentTarget.classList.contains('ol-collapsed')) {
    console.log('Collapsed');
  } else {
    console.log('Opened');
  }
});

如果您想观察来自 OpenLayers 的事件而不关心单击发生的位置(因为缩放事件可以通过鼠标滚轮、双击地图或单击 +/- 缩放按钮来生成),您可能想要监听ol.View事件

map.getView().on('change:rotation', evt => {
  console.log('Rotation event', evt);
})

map.getView().on('change:resolution', evt => {
  console.log('Resolution event', evt);
})

PS:您可以在视图上侦听其他事件,但我让您在 API 中检查它们


推荐阅读