10

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.

yaugenka
  • 829
  • 2
  • 12
  • 23

2 Answers2

14

Here is a simplified version of that custom control example.

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

var handleRotateNorth = function(e) {
    map.getView().setRotation(0);
};

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

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

var RotateNorthControl = new ol.control.Control({
    element: element
});
map.addControl(RotateNorthControl);

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

yaugenka
  • 829
  • 2
  • 12
  • 23
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) {
        myControl.customFunction(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';
    custom_element.appendChild(anchor_element);

    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 {
    content:"Cycle";
}

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/

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