1

I'm making a map in Leaflet and I have up to two labels per marker:

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>$456K </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);

What I'd like to do is hide the labels until the user zooms in past a certain threshold. Does anyone know how to do that? Moreover, if it is possible to only display labels after a certain zoom, is there a way so that some labels are always shown (like Label 1.1 above) whereas others only appear after passing the zoom threshold (like Label 1.2 above)?

I try adding this code, which has worked for another poster, and it didn't work for me (my map is called 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();

I've learned the appendedLabel portion of my code isn't standard for Leaflet. I found it here (last post) when trying to trouble shoot an issue of adding multiple labels.

6
  • Please edit your question and add info where does this .appendedLabel method comes from. It's not part of standard Leaflet. You are also using Leaflet 0.7.7 which is way obsolete. Any reason for that?
    – TomazicM
    Commented Feb 25, 2021 at 10:30
  • Done. I'm using Leaflet 0.7.7 because I'm a total newbie and didn't know better. Didn't mean to end up using something obsolete.
    – andy_d
    Commented Feb 25, 2021 at 16:22
  • Sorry for my nonsense comment, .appendedLabel is custom property, not method, so it's OK. What's not OK are .showLabel and hideLabel methods which do not exist.
    – TomazicM
    Commented Feb 25, 2021 at 16:48
  • Got it. I thought they did exist based on the post I linked to above and this thread here: github.com/Leaflet/Leaflet.label/issues/83. I'll start looking for a different method. Thanks!
    – andy_d
    Commented Feb 25, 2021 at 16:51
  • You could achieve what you want by putting those labels that you want to hide, not directly on map but in a separate group layer. You can then add/remove this group layer to the map depending on zoom.
    – TomazicM
    Commented Feb 25, 2021 at 16:52

1 Answer 1

1

To avoid dealing with each marker separately, you can put those labels that you want to show only at certain zoom level, not directly on map but in a separate group layer. You can then add/remove this group layer to the map depending on zoom.

Code could then look something like this:

var markerGroup = L.layerGroup();

function createLabel(layer, text, count){
  .
  .
  .
  var label = L.marker(layer.getLatLng(),{icon: icon});
  layer.appendedLabel = label;
  if (count == 1)
    label.addTo(mymap);
  else {
    label.addTo(markerGroup);
  }
  .
  .
  .
}

var show_label_zoom = 20;      
var currZoom = mymap.getZoom();

function show_hide_labels() {
  var zoom = mymap.getZoom();
  if (zoom > currZoom) {
    if (zoom == show_label_zoom) markerGroup.addTo(mymap);
    }
  else {
    if (currZoom == show_label_zoom) markerGroup.removeFrom(mymap);
  }
  currZoom = mymap.getZoom();
}

mymap.on('zoomend', show_hide_labels);
if (currZoom >= show_label_zoom) markerGroup.addTo(mymap);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.