add/remove legends when layer selected

2,554 views
Skip to first unread message

cel...@gmail.com

unread,
Apr 3, 2014, 10:22:41 PM4/3/14
to leafl...@googlegroups.com
Hi All,

I'm new to leaflet/javascript and have been struggling to get legends to show only when a specific layers is selected. I have three layers and would like to have the legends only appear when a specific layer is selected from the control. Any guidance would be greatly appreciated. Below is the code for my map:

<title>Test map</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script src="http://...src/proj4-compressed.js"></script>
    <script src="http://...src/proj4leaflet.js"></script>
<style type="text/css">
body {
padding: 0;
margin: 0;
}
#map {
width: 800px;
height: 500px;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.legend {
line-height: 18px;
color: #555;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
var crs = new L.Proj.CRS('EPSG:3575',
'+proj=laea +lat_0=90 +lon_0=10 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs',
{
resolutions: [
16384, 8192, 4096, 2048, 1024, 512, 256, 128,
64, 32, 16, 8, 4, 2, 1, 0.5
],
origin: [90, 10]
}),
map = new L.Map('map', {
crs: crs,
continuousWorld: true,
worldCopyJump: false
});


layers: 'land,permafrost_extent,country_borders,north_pole_geographic,arctic_circle,country_labels',
format: 'image/png',
maxZoom: 16,
minZoom: 0,
continuousWorld: true,
attribution: '&copy; <a href="http://nsidc.org">NSIDC</a>'
}).addTo(map);

layers: 'land,country_borders,treeline,north_pole_geographic,arctic_circle,country_labels,geographic_features_sea',
format: 'image/png',
transparent: true,
maxZoom: 16,
minZoom: 0,
continuousWorld: true,
attribution: '&copy; <a href="http://nsidc.org">NSIDC</a>'
}).addTo(map);

var baseMap1 = L.tileLayer.wms('http://wms.alaskamapped.org/bdl/', {
layers: 'BestDataAvailableLayer',
format: 'image/jpeg',
maxZoom: 16,
minZoom: 0,
continuousWorld: true,
attribution: '&copy; <a href="http://www.alaskamapped.org/data/wms-wfs-wcs-web-service-feeds">SDMI</a>'
}).addTo(map);

map.setView([90, 180], 0);
// Set map bounds
map.fitBounds([[50, -180],
    [90, 180]]);
// add legend 1
var legend1 = L.control({position: 'bottomright'});
legend1.onAdd = function(map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML += "<iframe src='"+ "http://nsidc.org/cgi-bin/atlas_north?service=WMS&version=1.1.1&request=GetLegendGraphic&format=image/png&layer=treeline" +"' width='300' height='20' frameborder='0'></iframe>"
return div;
};
legend1.addTo(map);
// add legend 2
var legend2 = L.control({position: 'topright'});
legend2.onAdd = function(map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML += "<iframe src='"+ "http://nsidc.org/cgi-bin/atlas_north?service=WMS&version=1.1.1&request=GetLegendGraphic&format=image/png&layer=permafrost_extent" +"' width='260' height='80' frameborder='0'></iframe>"
return div;
};
legend2.addTo(map);
// add layers and control
var baseMaps = {
"Permafrost": baseMap2,
"Treeline": baseMap3,
"Satellite": baseMap1
};
   
  L.control.layers(baseMaps).addTo(map);
</script>
</body>
</html>

cel...@gmail.com

unread,
Apr 4, 2014, 12:50:06 PM4/4/14
to leafl...@googlegroups.com

I just realized I could create a specific example using jsfiddle to share with everyone and sorry for including all my code previously.

http://jsfiddle.net/gerlis/T8DHb/3/

I have three layers, one of which I would like to have no legend and two others that have a corresponding legend. I came across an example that may adequate for my problem, but have not been able to make it work:

// Add and remove legend from layers
  map.on('overlayadd', function (eventLayer) {
  // Switch to the Permafrost legend...
  if (eventLayer.name === 'Permafrost') {
    this.removeControl(legend1);
    legend2.addTo(this);
  } else { // Or switch to the treeline legend...
    this.removeControl(legend2);
    legend1.addTo(this);
}});

Thanks in advance for your help.


Message has been deleted

k_man_au

unread,
Apr 9, 2014, 2:24:15 AM4/9/14
to leafl...@googlegroups.com

This is some code I've modified from a static example to do exactly what you need... I can't remember which example, so apologies to the original author who inspired it. Pretty much just need to create a single legend object, and then swap out the contents  ( by calling - legend.update("MyLayerStyle"); )

If you need to hide the legend use legend.removeFrom(map); , and to bring it back legend.addTo(map);


<!-- Legend -->
    var legend = new (L.Control.extend({
     options: { position: 'bottomright' }
    }));
    
    legend.onAdd = function (map) {
     this._div = L.DomUtil.create('div', 'info legend');      
     this.update();
     return this._div;
    };
    
    legend.update = function (style) {      
      if (style  == "Style 1" || style  == "Style 2")
       {    
        vals = [0, 1];
        labels = ["Desc 1", "Desc 2"];
        colors = ["#FF0000", "#00FF00"];
       }
       else if (style  == "Style 3")
       {    
        vals = [0, 1];
        labels = ["Desc 1", "Desc 2"];
        colors = ["#FF0000", "#00FF00"];
       }        
      
      for (var i = 0; i < vals.length; i++) {
       this._div.innerHTML += '<i style="background:' + colors[i] + '"></i> ' + vals[i] + labels[i] + '<br />';
      }
    };     
    <!-- end legend -->


CSS needed -

  .info {           
    background: rgba(255,255,255,0.8);   
    border-radius: 5px;
     padding: 10px;
   }

   .legend {
      line-height: 25px;
      color: #555;
      width: 150px;
    }

Hope it helps.... :)

Reply all
Reply to author
Forward
0 new messages