Users of your mapping application may feel more comfortable navigating around the map with the use of a keyboard. This may also fulfill some accessibility requirements of the app. For whatever reason, we'll demonstrate how to add and customize keyboard control for a map.
The source code of this recipe can be found in ch04/ch04-keyboard-pan-zoom/
.
To enable the arrow keys to pan and the plus and minus keys to zoom, follow these steps:
Create an HTML file and include the OpenLayers dependencies and a
div
element for the map.Create a custom JavaScript file and set up both keyboard interactions, as follows:
var keyboardPan = new ol.interaction.KeyboardPan({ duration: 90, pixelDelta: 256 }); var keyboardZoom = new ol.interaction.KeyboardZoom({ duration: 90 });
Instantiate and configure the map, making sure to add the keyboard interactions:
new ol.Map({ view: new ol.View({ zoom: 10, center: [-12987415, 3851814] }), target: 'js-map'...