Leaflet Tooltips – How to Show/Hide All Tooltips at Once

layersleaflettooltip

I use a for loop to add tooltips to my Leaflet map by reading the lat and lon coordinates from a .txt file.

 for (var i = 0; i < lines.length; i++) {
   ...

   L.tooltip({
             permanent: true,
             direction: 'auto',
             className: 'my-label'
           })
         .setContent("Hello")
         .setLatLng([lat,lon])
         .addTo(map);
    ...
    })

I would like to put the tooltips on their own layer in order to make them visible or invisible by clicking on the layer check box in the layers panel (see L.control.layers)

How can I put all tooltips on a specific layer?

Best Answer

Simply create a layer group and instead of adding tooltips directly to the map, add them to the layer group. You can then add this layer group to layer control as an overlay.

var tooltipLayer = L.layerGroup();

for (var i = 0; i < lines.length; i++) {
  ...
  L.tooltip({
    permanent: true,
    direction: 'auto',
    className: 'my-label'
  })
  .setContent("Hello")
  .setLatLng([lat,lon])
  .addTo(tooltipLayer);
  ...
});