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?

Tangnar
  • 1,362
  • 10
  • 18

3 Answers3

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.

Tangnar
  • 1,362
  • 10
  • 18
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.

Alex Leith
  • 13,453
  • 30
  • 69
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/

  • 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 Sep 09 '15 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)... – Alexander Parshin Sep 09 '15 at 14:15