On the official openlayers site there is a custom control example which demonstration a class base control.

Can anyone give an example of a simple custom control without class usage?

According to the ol.control.Control specification, it should be possible to create one using the following statement

var myControl = new ol.control.Control({element: myElement});

but I'm quite new to javascript and cannot figure out yet how to use it.


2 Answers 2


Here is a simplified version of that custom control example.

var button = document.createElement('button');
button.innerHTML = 'N';

var handleRotateNorth = function(e) {

button.addEventListener('click', handleRotateNorth, false);

var element = document.createElement('div');
element.className = 'rotate-north ol-unselectable ol-control';

var RotateNorthControl = new ol.control.Control({
    element: element

You can see complete code at http://jsfiddle.net/yaugenka/62y73Ls8/7/

// Preparation for the custom control:

    var anchor_element = document.createElement('a');
    anchor_element.href = '#custom_href';
    anchor_element.className = 'custom_anchor';

    var this_ = this;
    var handleCustomControl = function (e) {

    anchor_element.addEventListener('click', handleCustomControl, false);
    anchor_element.addEventListener('touchstart', handleCustomControl, false);

    var custom_element = document.createElement('div');
    custom_element.className = 'myCustomControl ol-unselectable';

    myControl = new ol.control.Control({
        className: 'myControl',
        element: custom_element,
        target: document.getElementById("myCustomControl")


CSS-rule (to be able to click on the hyperlink):

.custom_anchor:before {

I gave it a quick try and can use a custom Control: http://jsfiddle.net/expedio/onn6g33c/

Probably it's a better choice to set up a control like this if it's getting a bit more complex: http://jsfiddle.net/expedio/j4duqc9s/

  • I'm trying to make that example from openlayers site as simple as possible and following your example have got the following. jsfiddle.net/yaugenka/62y73Ls8/3 Can you check what is missing there?
    – yaugenka
    Commented Oct 1, 2015 at 9:22
  • the value to rotate is zero, not the letter 'o' and it's ol.control.Control and not ol.Control.Control: jsfiddle.net/expedio/62y73Ls8/6 ;)
    – Thomas B
    Commented Oct 1, 2015 at 19:06
  • Now it works! Thank you @TomasB. I'll add an extra answer with this code.
    – yaugenka
    Commented Oct 1, 2015 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.