标签仅在缩放 Leaflet 时出现

Labels only appear if zoom Leaflet

我正在 Leaflet 中制作地图,每个标记最多有两个标签:

var redIcon = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

var marker1 = L.marker([25.777085, -80.193935], {icon: redIcon}).addTo(mymap);
var marker2 = L.marker([25.759461, -80.204921], {icon: redIcon}).addTo(mymap);

marker1.bindPopup('<div style="line-height: 1.2em;"><table align="center" border="0"  cellpadding=".25" cellspacing=".25" width="95%"><tbody><tr><td colspan="2"><div style="padding: 0.1em; background-color: rgb(0,0,255); text-align: center;"><b style="color:white;">Number 1</b></div></td></tr><tr><td style="text-align: center;"> <strong>6K </strong><br><strong>2 </strong>bd |&nbsp;<strong>2 &nbsp;</strong>ba |&nbsp;<strong>1,008 </strong>sqft<br><img src="https://static.pexels.com/photos/189349/pexels-photo-189349.jpeg" height="50px" width="50px"/></td><td style="text-align: left;">&nbsp;</td></tr></tbody></table></div>');
marker1.on('mouseover', function (e) {
            this.openPopup();
        });
        marker1.on('mouseout', function (e) {
            this.closePopup();
        });

function createLabel(layer, text, count){
    //removeLabel(layer);
    var icon = createStaticLabelIcon(text);
  var testspan = document.createElement("span");
  document.body.appendChild(testspan); 

  testspan.className = "textwidth";
  testspan.style.fontSize = "10px";
  testspan.innerHTML = text;
  var width = testspan.clientWidth +11;
  var posY = 0;
  if( count == 1){
     posY = -4;
  } else if( count == 2){
     posY = -24;
  }

  icon.options.iconAnchor = [width  / 2, posY]; //That the label is centered

  var label = L.marker(layer.getLatLng(),{icon: icon}).addTo(mymap);
  layer.appendedLabel = label;

  document.body.removeChild(testspan); 
}

function createStaticLabelIcon(labelText) {
    return L.divIcon({
        className: "leaflet-marker-label",
        html: '<span class="leaflet-marker-iconlabel" style="background: #CB2B3E; color: #FFFFFF;";>'+labelText+'</span>',
        text: labelText,
    });
}

createLabel(marker1, "Label 1.1",1);
createLabel(marker1, "Label 1.2",2);
createLabel(marker2, "Label 2",1);

我想做的是隐藏标签,直到用户放大超过某个阈值。有谁知道这是怎么做到的吗?此外,如果可以只在某个缩放后显示标签,有没有办法让一些标签始终显示(如上面的标签 1.1),而其他标签仅在通过缩放阈值后显示(如上面的标签 1.2)?

更新:

这是我试过但没有用的方法。我尝试了 solution from this post.

这是我的地图 mymap:

var mymap = L.map('mapid').setView([25.7741728, -80.19362], 12);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken:'pk.eyJ1IjoiamFtZXNyYSIsImEiOiJja2xoNnVzdmUwMGxpMnVtZ2NheGxlanFqIn0.dx40peACrjwV9CfQpFhGpg'
}).addTo(mymap);

然后我添加了一些代码,这些代码应该只显示低于特定缩放级别的标签,但它不起作用:

var show_label_zoom = 20; // zoom level threshold for showing/hiding labels
var labels_visible = true;
function show_hide_labels() {
    var cur_zoom = mymap.getZoom();
    if(labels_visible && cur_zoom < show_label_zoom) {          
        labels_visible = false;
        mymap.eachLayer(layer => layer.hideLabel && layer.hideLabel());               
    }
    else if(!labels_visible && cur_zoom >= show_label_zoom) {           
        labels_visible = true;
        mymap.eachLayer(layer => layer.showLabel && layer.showLabel());               
    }
}
mymap.on('zoomend', show_hide_labels);
show_hide_labels();

关于为什么这不起作用的任何想法?

更新二:

我试图实现这个线程的答案,但它仍然没有用。这是整个脚本。我是不是遗漏了一些重要的细节,导致它无法正常工作?

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>
   <link type="text/css" rel="stylesheet" href="style.css" />
  <!-- Make sure you put this AFTER Leaflet's CSS -->
 <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
   integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
   crossorigin="">
   </script>
  <style> 
    #mapid { height: 350px; }
  </style>
</head>
<body>
  <div id="mapid"></div>
  <script>
    var mymap = L.map('mapid').setView([25.7741728, -80.19362], 12);

    var fg = L.featureGroup().addTo(mymap);

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox/light-v10',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'pk.eyJ1IjoiamFtZXNyYSIsImEiOiJja2xoNnVzdmUwMGxpMnVtZ2NheGxlanFqIn0.dx40peACrjwV9CfQpFhGpg'
}).addTo(mymap);


var redIcon = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

var marker1 = L.marker([25.777085, -80.193935], {icon: redIcon}).addTo(mymap);
var marker2 = L.marker([25.759461, -80.204921], {icon: redIcon}).addTo(mymap);

function createLabel(layer, text, count){
    //removeLabel(layer);
  var icon = createStaticLabelIcon(text, count);
  var testspan = document.createElement("span");
  document.body.appendChild(testspan); 

  testspan.className = "textwidth";
  testspan.style.fontSize = "10px";
  testspan.innerHTML = text;
  var width = testspan.clientWidth +11;
  var posY = 0;
  if( count == 1){
     posY = -4;
  } else if( count == 2){
     posY = -24;
  }

  icon.options.iconAnchor = [width  / 2, posY]; //That the label is centered

  var label = L.marker(layer.getLatLng(),{icon: icon}).addTo(fg);
  layer.appendedLabel = label;

  document.body.removeChild(testspan); 
}

function createStaticLabelIcon(labelText, count) {
if (count == 1) {
        return L.divIcon({
        className: "leaflet-marker-label",
        html: '<span class="leaflet-marker-iconlabel" style="background: #fff; color: #000;";>'+labelText+'</span>',
        text: labelText,
    });
    }
    else { 
    return L.divIcon({
        className: "leaflet-marker-label",
        html: '<span class="leaflet-marker-iconlabel" style="background: #CB2B3E; color: #FFFFFF;";>'+labelText+'</span>',
        text: labelText,
    });}
}

createLabel(marker1, "Label 1.1",1);
createLabel(marker1, "Label 1.2", 2);
createLabel(marker2, "Label 2",1);

var show_label_zoom = 20; // zoom level threshold for showing/hiding labels
function show_hide_labels() {
    var cur_zoom = mymap.getZoom();
    if(cur_zoom < show_label_zoom && map.hasLayer(fg)) {       
        mymap.removeLayer(fg);            
    } else if(!map.hasLayer(fg) && cur_zoom >= show_label_zoom) {            
        mymap.addLayer(fg);                 
    }
}
mymap.on('zoomend', show_hide_labels);
show_hide_labels();

  </script>
</body>
</html>

不是将标签添加到地图,而是将其添加到 L.featureGroup:

var fg = L.featureGroup().addTo(map);
...
function createLabel(layer, text, count){
   ...
   var label = L.marker(layer.getLatLng(),{icon: icon}).addTo(fg);
   ...
} 

然后在缩放时删除/添加组:

function show_hide_labels() {
    var cur_zoom = mymap.getZoom();
    if(cur_zoom < show_label_zoom && mymap.hasLayer(fg)) {       
        mymap.removeLayer(fg);            
    } else if(!mymap.hasLayer(fg) && cur_zoom >= show_label_zoom) {            
        mymap.addLayer(fg);                 
    }
}
mymap.on('zoomend', show_hide_labels);
show_hide_labels();