Search code examples
javascriptleaflet

Hide tooltip in leaflet for a zoom range


I may have a lot of marker in some area but this is not really useful to display the tooltip if there is 5 of them in the same area, like this screen :

enter image description here

Is it possible to hide those tooltip from a zoom range ? For example, hide tooltip from the level 0 to 5.

Maybe using the getZoom() method with an event on the zoom like :

if the user zoom {
    if (getZoom() < 5) {
      hide all tooltip
    }
}

Or something more complicated but better which could hide it if there is too many marker in the same area ?


Solution

  • To hide tooltips based on zoom range, see this Leaflet issue conversation that references this JS bin. Code repeated below:

    var lastZoom;
    map.on('zoomend', function() {
      var zoom = map.getZoom();
      if (zoom < 15 && (!lastZoom || lastZoom >= 15)) {
        map.eachLayer(function(l) {
          if (l.getTooltip) {
            var toolTip = l.getTooltip();
            if (toolTip) {
              this.map.closeTooltip(toolTip);
            }
          }
        });
      } else if (zoom >= 15 && (!lastZoom || lastZoom < 15)) {
        map.eachLayer(function(l) {
          if (l.getTooltip) {
            var toolTip = l.getTooltip();
            if (toolTip) {
              this.map.addLayer(toolTip);
            }
          }
        });
      }
      lastZoom = zoom;
    })
    

    Edit: also, see this StackOverflow question.