0
votes

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

Update:

Here's something I tried that didn't work. I tried the solution from this post.

Here's my map called 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);

Then I added some code that should only present labels below a specific zoom level but it didn't work:

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

Any ideas on why this didn't work?

Update 2:

I tried to implement the answer to this thread but it still didn't work. Here is the entire script. Am I missing some important detail that is preventing this from working correctly?

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/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/[email protected]/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>
1

1 Answers

1
votes

Instead of adding the label to the map, add it to a L.featureGroup:

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

And then remove / add the group while zooming:

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