Leaflet折线的标签

5
我想展示带有折线的标签/文本,这是我的代码。
function displayDottedLine(latA, longA, latB, longB, label) {
    var pointA = new L.LatLng(latA, longA);
    var pointB = new L.LatLng(latB, longB);
    var pointList = [pointA, pointB];
    var firstpolyline = new L.Polyline(pointList, {
        color: 'white',
        weight: 1.5,
        opacity: 0.5,
        dashArray: "10 10",
        smoothFactor: 1
    });
    firstpolyline.addTo(map);
}

这个函数里有一个标签参数,我需要把这个标签附加到折线上。

提前致谢。

1个回答

5
您可以尝试使用leaflet.textpath.js插件。

window.addEventListener('load', function() {
  var map = L.map('map').setView([51.328125, 42.2935], 18);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  var plane = L.polyline([
    [3.33984375, 46.6795944656402],
    [29.53125, 46.55886030311719],
    [51.328125, 42.293564192170095],
  ]).addTo(map);
  map.fitBounds(plane.getBounds());
  
  plane.setText('SAMPLE TEXT', {center: true});
});
#map {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-textpath@1.2.0/leaflet.textpath.min.js"></script>

<div id="map"></div>


“样本文本”的颜色是黑色的,我们能改变它的颜色吗?实际上我的背景是黑色的。 - Muhammad Waqar
3
@MuhammadWaqar 你可以像这样做:plane.setText('示例文本', {center: true, attributes: {fill: '#fff' }}); - User863
@MuhammadWaqar 在这里探索更多选项:https://github.com/makinacorpus/Leaflet.TextPath#options - User863

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