My intention is to add transparency sliders to each layer in a L.control.layers. I was going to use a simple HTML5 slider <input>, demonstrated here:


However, when I add an <input> to the legend string in a L.control.layers, I get an error:

leaflet.js:12457 Uncaught TypeError: Cannot read property 'layer' of undefined(…)
_checkDisabledLayers @ leaflet.js:12457
_addItem @ leaflet.js:12411
_update @ leaflet.js:12325
onAdd @ leaflet.js:12174
addTo @ leaflet.js:11610
(anonymous function) @ index.html:144

Removing the <input> fixes the error. What's the explanation?


Since your question is, literally:

What's the explanation?

I'm going to give you an explanation, and not a solution :-)

The Leaflet code for L.Control.Layers iterates through the radio buttons / checkboxes frequently, to check which buttons/boxes to mark as enabled.

In order to do so, it uses this one line of code (in the _onInputClick and _checkDisabledLayers private methods):

    var inputs = this._form.getElementsByTagName('input'),

This iterates through all the checkboxes and radio buttons inside the control. The downside is that, due to the way the code is written right now, it also iterates through any other <input> elements inside the control.

In other words: L.Control.Layers expects that all the <input>s inside it are either a checkbox or a radio button that enables/disables a leaflet layer. That's why Leaflet expects every <input> element to have a layerId property here:

        layer = this._getLayer(input.layerId).layer;

See input.layerId? That's what's triggering your error.

| improve this answer | |
  • Makes perfect sense. So without Leaflet checking explicitly for layerId as part of its identification of the layer checkboxes/radio buttons, it's not possible to put an <input> in a layers control? I'll try adding a layerId property to my slider purely out of curiosity (and mischief), but one imagines that will fundamentally break everthing. – Tom Chadwin Nov 18 '16 at 15:06
  • 1
    See github.com/Leaflet/Leaflet/issues/5116 :-D – IvanSanchez Nov 18 '16 at 15:09

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.