[GIS] Implementing non-default keyboard shortcuts in Openlayers2

javascriptopenlayers-2

Following on from this thread, I am trying to implement @Aragon's suggestion and add some keyboard shortcuts to OpenLayers via a handleKeyEvent method in OpenLayers.Handler.Keyboard. This ought to be a simple task that many people implement but for some reason I'm just not getting it.

var keyboardControl = new OpenLayers.Control();

var keyHandler = new OpenLayers.Handler.Keyboard(keyboardControl, {
    handleKeyEvent: function(evt) {
            alert("You pressed a key!");
            switch(evt.keyCode) {
                case 87:
                    doSomething([0, 1]);
                case 83:
                    doSomething([0,-1]);
                case 65:
                    doSomething([1,0]);
                case 68:
                    doSomething([-1,0])
            }
        },
});

function doSomething(vals){
    alert("Something will happen here eventually...");
};

map.addControl(keyboardControl);

I get no errors but neither of my alerts get fired. What am I doing wrong?

Best Answer

First of all you have to activate your new key handler :

keyHandler.activate();

You may also work a little on your callbacks. You will find a working example based on your code at the following URL : http://www.empreinte-urbaine.eu/mapping/ol_keyboard.html