Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  177] [ 6]  / answers: 1 / hits: 33492  / 8 Years ago, thu, september 29, 2016, 12:00:00

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


More From » jquery

 Answers
17

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:




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);

//L.circle([48.85, 2.35], {radius: 1000}).bindTooltip(test).addTo(map);
L.rectangle([
[48.84, 2.34],
[48.86, 2.36]
]).bindTooltip(test).addTo(map);

html, body, #map {
height: 100%;
margin: 0;
}

<script src=https://unpkg.com/[email protected]/dist/leaflet.js></script>
<link href=https://unpkg.com/[email protected]/dist/leaflet.css rel=stylesheet />
<div id=map></div>






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:




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);

//L.circle([48.85, 2.35], {radius: 1000}).bindTooltip(test).addTo(map);
L.rectangle([
[48.84, 2.34],
[48.86, 2.36]
]).bindTooltip(test, {
sticky: true
}).addTo(map);

html, body, #map {
height: 100%;
margin: 0;
}

<script src=https://unpkg.com/[email protected]/dist/leaflet.js></script>
<link href=https://unpkg.com/[email protected]/dist/leaflet.css rel=stylesheet />
<div id=map></div>




[#60556] Tuesday, September 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylan

Total Points: 734
Total Questions: 91
Total Answers: 102

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;