Add a title to leaflet layers control

Viewed 5294

Does anyone have a method for adding a title to a leaflet layers control? Just a line of text, for example "Available layers." Ideally I'd like to add a link to the text as well.

I thought it would be simple, but I haven't been able to find a solution. I tried methods similar to this question (radio button/checkbox remains after adding "dummy" layer) and this question (adds div to end of layers, seems more complex than my needs). Unfortunately with my experience level, I haven't been able to connect the dots. Any suggestions?

4 Answers

#Leaflet1.7
Here is the vanilla JS minimal solution.

// 0. Your's WMS layers:      
var fooLayers = {
      "Aaa" : ign_ari,
      "Bbb" : ign_cri,
      "Ccc" : ign_grvi
};

// 1. start with Control
var fooLegend = L.control({position: 'topleft'});

fooLegend.onAdd = function () {
      var div = L.DomUtil.create('div');
      // here is Your part:
      div.innerHTML = '<span class='your-class'>Your Title Text</span>';
      return div;
};
fooLegend.addTo(map);

var fooCtrl = L.control.layers(fooLayers, null,
              {collapsed : false, position: 'topleft'})
              .addTo(map);

//
// Nothing unusual, until now:
var fooCtrlDiv = fooCtrl.getContainer();
fooCtrlDiv.insertBefore(fooLegend.getContainer(), fooCtrlDiv.firstChild);

Leaflet 1.7: Addition to @Mruk's answer: If you want to use collapsed: true, then you have to dig a little bit deeper in the DOM tree:

const fooCtrlDiv = fooCtrl.getContainer();

fooCtrlDiv
  .querySelector('.leaflet-control-layers-list')
  .insertBefore(
    fooLegend.getContainer(),
    layerControlDiv.querySelector('.leaflet-control-layers-list').firstChild
  );
Related