4

In Leaflet it's possible to bind one or more tooltips to an individual marker, or a layer, or the base map object.

enter image description here

How can I close all open tooltips that have been bound to the map object?

var map = L.map("map");
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png").addTo(map);
map.setView([48.85, 2.35], 12);

// Define some tooltips against the map object
var tooltip1 = map.openTooltip("tooltip 1",[48.84, 2.34]);
map.openTooltip("tooltip 2",[48.83, 2.33]);
map.openTooltip("tooltip 3",[48.82, 2.32]);

// Attempt to close tooltips, individually or en masse - neither works
map.closeTooltip(tooltip1);
map.closeTooltip();

See also the JS Fiddle version of the above code.

2 Answers 2

5

You can get all layers from your map, and remove them from the map. To avoid removing the tile layer (background), filter with if(layer.options.pane === "tooltipPane").

map.eachLayer(function(layer) {
    if(layer.options.pane === "tooltipPane") layer.removeFrom(map);
});

Fiddle: https://jsfiddle.net/3v7hd2vx/392/

2
  • ah, I didn't realise that Leaflet creates a separate layer for each tooltip. Nice one! Commented Sep 5, 2017 at 22:39
  • 1
    Apparently Leaflet creates a new 'hybrid' layer when a tooltip is added directly on the map (not bound to another layer). I think the best way to do it would be to create an invisible marker layer and to bind the tool tip to it.
    – thibautg
    Commented Sep 6, 2017 at 6:25
0

Quick and dirty solution below.

js:

// checked is from a toggle component...
const tooltipPanes = document.getElementsByClassName("leaflet-tooltip-pane");
if (checked) {
  tooltipPanes[0].classList.remove("tooltip-hidden");
} else {
  tooltipPanes[0].classList.add("tooltip-hidden");
}

css:

.tooltip-hidden {
  display: none;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.