how to add a html title (tooltip) to a leaflet.js polygon?

30,429

Leaflet 1.0.0 has a new built-in L.tooltip class that deprecates the Leaflet.label plugin. The tooltip points at the shape center and does not move with the mouse.

L.polygon(coords).bindTooltip("my tooltip").addTo(map);

Demo: https://jsfiddle.net/3v7hd2vx/91/


To address OP's comment about tooltip being displayed at the polygon center, which can be out of view when the polygon is very big and current zoom is high, you can use the sticky option:

L.polygon(coords).bindTooltip("my tooltip", {
  sticky: true // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
}).addTo(map);

Updated demo: https://jsfiddle.net/3v7hd2vx/402/

Share:
30,429
JW-Munich
Author by

JW-Munich

Updated on July 09, 2022

Comments

  • JW-Munich
    JW-Munich almost 2 years

    I have a leaflet map and I would like to add a html title (tooltip) to my polygon. If I use plain JQuery:

    $('<title>my tooltip</title>').appendTo()
    

    The title gets added to the DOM but is not visible. See here for more details but if I follow that solution, I can no longer use the leaflet features.

    I also tried the leaflet.label plugin but the label moves around with the mouse pointer. I just want the standard browser title tooltip that appears in one position shortly after on hover)

    thanks for your help

  • JW-Munich
    JW-Munich over 7 years
    oh thanks, It looks good but my polygon (well, rectangle) is the full size of the map. It seems the tooltip gets lost somewhere
  • ghybs
    ghybs over 6 years
    Added sticky option to address above issue.
  • redfox05
    redfox05 over 5 years
    Also as a side note, I did not want the arrow for the tooltip on the shape, so centering it using direction: 'center' put the label in the middle without an arrow