Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add keyboard-event to Openlayers map

I'm unable to add a custom keyboard-event to Openlayers, and can't figure out why. Might it be a bug in relation to the already existing keyboard-events included in Openlayers?

I've tried the following with no result:

this.map.getViewport().addEventListener('keydown', (e) => {
  console.log(e);
}, true)


document.getElementById('map').addEventListener('keydown', (e) => {
  console.log(e);
})

Listening to clicks on the same elements work fine:

this.map.getViewport().addEventListener('click', (e) => {
  console.log(e);
}, true)

document.getElementById('map').addEventListener('click', (e) => {
  console.log(e);
})

Any solutions to this?

like image 534
Koronag Avatar asked Oct 29 '25 10:10

Koronag


2 Answers

As mentioned map needs focus. You can use the FocusMap interaction of ol-ext to focus on the map when ckick on it.

See https://github.com/Viglino/ol-ext/blob/master/src/interaction/FocusMap.js

This example use it to handle ctrl+c/ctrl+v on a map. https://viglino.github.io/ol-ext/examples/interaction/map.interaction.copypaste.html

like image 135
Viglino Jean-Marc Avatar answered Nov 01 '25 00:11

Viglino Jean-Marc


This problem as Mike mentioned is occurring because of focus issues.
I faced this problem a few months ago, so I searched my old projects and find this:

<div id="map" tabindex="0"></div>

After assigning a tab index to an element you can use javascript focus(). in order to use it (after assigning tab index) use this:

document.getElementById('map').focus();

I think this could help.
Also, there is an answer I found months ago is here. You can find more info about focusing.

like image 27
Mahdi Mahmoodian Avatar answered Oct 31 '25 23:10

Mahdi Mahmoodian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!