如何将工具提示绑定到传单的边缘 L.Circle?

How to bind a tooltip to the edge of a leaflet L.Circle?

我有一张传单地图,其中我使用 L.Circle 创建了几个圆圈,这些圆圈的半径和位置会实时更新。我想将工具提示或类似内容绑定到这些将显示一些文本的圆圈的边缘。我附上了我想要实现的目标的图像。

我使用以下方法创建了我的圈子:

circle = new L.Circle(point, {
    color: '#00F',
    opacity: 0.8,
}).addTo(map);

这很好用并产生了以下结果:

我无法复制如上所示的连接文本,因为我无法将任何内容绑定到圆圈。将文本字段动态绑定到圆半径中心底部的最佳方法是什么?

您可以将 Tooltip 绑定到圆上,并使用其 offset 选项将其放置在底部边缘。然而,这很尴尬,因为偏移量是以像素为单位指定的,因此您必须将圆半径从米转换为当前缩放级别的像素。除了考虑圆半径的变化外,您还必须在地图缩放时重新定位工具提示,而 Circle class 没有方便的事件来告诉您何时这样做。

一种更可靠的方法是在正确的位置创建一个不可见的标记,并将工具提示绑定到该标记(如 中所建议)。标记可以使用圆的坐标而不是像素偏移来定位,并且在地图缩放时会留在正确的位置。

要自动放置不可见标记,并在圆的坐标或半径发生变化时更新它,我们可以创建自定义 TipCircle class 来扩展法线 Circle 的功能.查看 CircleMarkersource code(Circle 的父 class)有助于找出要覆盖的函数:

L.TipCircle = L.Circle.extend({
  initialize: function(latlng, options, legacyOptions) {
    // Create invisible marker
    this._tip = L.circleMarker([0,0], {opacity: 0, radius: 0});
    // Initialize as a normal Circle
    L.Circle.prototype.initialize.call(this, latlng, options, legacyOptions);
  },
  redraw: function() {
    L.Circle.prototype.redraw.call(this);
    this._setTip();
  },
  onAdd: function() {
    L.Circle.prototype.onAdd.call(this);
    this._setTip();
    this._tip.addTo(map);
  },
  onRemove: function() {
    this._tip.remove();
    L.Circle.prototype.onAdd.call(this);
  },
  _setTip: function() {
    // Set the location for the tooltip to latitude of the bottom of the circle's
    // bounding box, and the longitude of its centre.
    this._tip.setLatLng([
      this.getBounds()._southWest.lat,
      this.getLatLng().lng]);
    // Set the label to the circle's radius in metres
    const tipText = String(this.getRadius());

    // Remove any old tooltip and attach the new one
    this._tip.unbindTooltip();
    this._tip.bindTooltip(tipText, {
                            direction: 'center',
                            permanent: true,
                            className: 'circleTip'
                          });
  }
});
L.tipCircle = (latlng, options, legacyOptions) => new L.TipCircle(latlng, options, legacyOptions);

您可以像使用普通 Circle 一样使用这个新的 TipCircle class:

circle = (new L.TipCircle(point, {color: '#00F', opacity: 0.8})).addTo(map);

它会自动显示工具提示,并在您用circle.setLatLng()circle.setRadius()更改时保持在正确的位置。上面的代码还将更改工具提示文本以显示圆的当前半径(以米为单位)。编辑 _setTip() 方法将其转换为 km,或任何您需要的格式。

您还可以添加一些 CSS 以使工具提示的格式更像您示例中的提示:

.circleTip {
  box-shadow: none;
  border: 1px solid blue;
  padding: 1px;
  font-size: x-small;
}