3

I would like to have layers listed in my layer control, but have their check boxes disabled when zoomed out beyond a certain level.

I am asking the same question that is found here, but with Leaflet instead of OpenLayers.

This is admittedly a "has this already been done" question. I could try to figure out if it can be translated easily from the OpenLayers example above, but maybe someone has accomplished this already?

3 Answers 3

2

This ended up being a little easier than I expected by using document.querySelectorAll to select checkboxes, and setting them to disabled=true.

Ended up finding help combining this answer from Stack Overflow with this about iterating over querySelectorAll (simple for loop).

Ended up with this:

var checks = document.querySelectorAll('[type = "checkbox"]'), i;
function disCheck() {
    for (i = 0; i < checks.length; ++i) {
        checks[i].disabled = true;

... with some more stuff following it, and calling it in my function that controls zoom stuff.

0

I think that the Leaflet layers control tries to keep things simple. You'll need to extend it to modify functionality to suit what you're trying to do, unfortunately.

0

You can extend L.Control.Layers in the following way:

var DisabledLayers = L.Control.Layers.extend({
    onAdd: function(map) {
        this._map = map;
        map.on('zoomend', this._update, this);
        return L.Control.Layers.prototype.onAdd.call(this, map);
    },

    onRemove: function(map) {
        map.off('zoomend', this._update, this);
        L.Control.Layers.prototype.onRemove.call(this, map);
    },

    _addItem: function(obj){
        var item = L.Control.Layers.prototype._addItem.call(this, obj);

        // implement your logic here
        // in this example layers are disabled below zoom 12
        if (this._map.getZoom() < 12) {
            $(item).find('input').prop('disabled', true);
        }

        return item;
    }
})

It allows you to implement activation/deactivation logic taking into account individual layers (it is not possible in case of external DOM elements modification).

Here is an example: http://jsfiddle.net/parshin/vgyyzkow/

2
  • True, it would be more difficult to modify individual layers, but I don't need to. Are there other advantages to extending the control over using the method I chose?
    – Tangnar
    Commented Sep 9, 2015 at 14:00
  • @Tangnar Another advantage I can see is that extended class handles dynamic addition/removal of layers in the control. All others are more theoretical (easy to reuse, all code in one place, etc)... Commented Sep 9, 2015 at 14:15

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.