如何为leaflet.js多边形添加HTML标题(工具提示)?

17

我有一个leaflet地图,我想给我的多边形添加一个HTML标题(工具提示)。如果我使用普通的JQuery:


$('<title>my tooltip</title>').appendTo()
标题被添加到DOM中但不可见。更多细节请参见此处,但如果我按照该解决方案操作,我将无法再使用leaflet功能。
我还尝试了leaflet.label插件,但标签会随着鼠标指针移动而移动。我只想要标准的浏览器标题工具提示,在悬停后在一个位置短暂出现。
感谢您的帮助。
1个回答

32

Leaflet 1.0.0增加了新的内置L.tooltip 类,取代了Leaflet.label 插件。该工具提示指向形状中心并且不随着鼠标移动。

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

演示:

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/leaflet@1.0.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.0.0/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>


针对OP有关工具提示显示在多边形中心的评论,可能会在多边形非常大且当前缩放比例很高时超出视野范围,您可以使用sticky选项:

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

更新演示:

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/leaflet@1.0.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.0.0/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>


哦,谢谢,看起来不错,但我的多边形(其实是矩形)是地图的全尺寸。似乎提示框在某个地方丢失了。 - JW-Munich
添加了 sticky 选项以解决上述问题。 - ghybs
另外顺带一提,我不想在形状上使用工具提示的箭头,因此使用 direction: 'center' 将其居中,使标签位于中间而没有箭头。 - redfox05

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接