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">
<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,
}).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,
}).addTo(map);
layers: 'BestDataAvailableLayer',
format: 'image/jpeg',
maxZoom: 16,
minZoom: 0,
continuousWorld: true,
}).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');
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');
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>