6

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.

6
// 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/

  • 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 Oct 1 '15 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 Oct 1 '15 at 19:06
  • Now it works! Thank you @TomasB. I'll add an extra answer with this code. – yaugenka Oct 1 '15 at 19:39
5

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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