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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With