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:
div element for the map.var keyboardPan = new ol.interaction.KeyboardPan({
duration: 90,
pixelDelta: 256
});
var keyboardZoom = new ol.interaction.KeyboardZoom({
duration: 90
});new ol.Map({
view: new ol.View({
zoom: 10,
center: [-12987415, 3851814]
}),
target: 'js-map',
layers: [
new ol.layer.Tile({source: new ol.source.Stamen({
layer: 'terrain'
})})
],
interactions: ol.interaction.defaults().extend([
keyboardPan, keyboardZoom
]),
keyboardEventTarget: document
});We've enabled full panning and zooming control directly from the keyboard in a small amount of code. Let's dive right in with the details.
var keyboardPan = new ol.interaction.KeyboardPan({
duration: 90,
pixelDelta: 256
});Both keyboard events are part of the OpenLayers ol.interaction object, which houses a whole host of interactions—DragPan and PinchRotate to name a few. We've customized some properties of the panning interaction, namely duration (in milliseconds) and pixelDelta (the amount of pixels the map moves in a single pan).
The similar keyboard zoom interaction has been passed a custom duration of 90 ms, as well. The keyboard zoom interaction has a delta property that accepts a number representing the quantity of zoom levels to execute per zoom alteration.
There are two specific map configuration properties that we'll look over next:
interactions: ol.interaction.defaults().extend([
keyboardPan, keyboardZoom
]),
keyboardEventTarget: documentAn instance of an OpenLayers map already comes with a variety of interactions enabled, of which KeyboardPan and KeyboardZoom are actually included. However, we've decided to customize the settings of these interactions, which are easily achieved by extending the array of the default interactions with the two modified keyboard ones.
By default, the keyboard events responsible for panning and zooming are only processed by OpenLayers if the map element (the div element containing the map) has focus. This means that the DOM element must have a tabindex property with a numeric value. This is easy enough to do, but, as our map is fullscreen, we have specified that the event target for keyboard events is the whole web page (document) via the map property, keyboardEventTarget. So, as long as the browser window has focus, keyboard interaction will work without the need to manually focus on the map DOM element by tabbing around.
Both keyboard interactions have a getActive method that can be called to determine whether or not the interaction is currently enabled.