Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 710
JW-Munich Avatar asked Sep 29 '16 12:09

JW-Munich


People also ask

How do you use tooltip in leaflet?

The following code adds a tooltip but it's not clickable: var tooltip = L. tooltip({ direction: 'center', permanent: true, interactive: true, noWrap: true, opacity: 0.9 }); tooltip. setContent( "Example" ); tooltip.

How do you make a polygon in leaflet?

Create a polygon using the L. Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon. var polygon = L. polygon(latlngs, {color: 'red'}); Add the polygon to the map using the addTo() method of the Polygon class.


1 Answers

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/

like image 150
ghybs Avatar answered Oct 11 '22 12:10

ghybs