Skip to content

Instantly share code, notes, and snippets.

@ernesmb
Last active February 6, 2016 12:19
Show Gist options
  • Save ernesmb/9aca76f45c1c55f7d8f5 to your computer and use it in GitHub Desktop.
Save ernesmb/9aca76f45c1c55f7d8f5 to your computer and use it in GitHub Desktop.
Hide/Show Legend with jQuery
<!DOCTYPE html>
<html>
<head>
<title>Hiding and showing legend | CartoDB.js</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
#map{position:relative;}
#bar{z-index: 2; position:absolute; top:0; right:0; margin:4px;}
</style>
</head>
<body>
<div id="map"></div>
<div id="bar">
<button id="hide" >hide legend</button>
<button id="show" >show legend</button>
</div>
<script>
function main() {
var map = L.map('map', {
zoomControl: false,
center: [40.418709, -3.703277],
zoom: 7
});
// add a nice baselayer from Stamen
L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen and CartoDB attribution'
}).addTo(map);
cartodb.createLayer(map, "https://team.cartodb.com/u/ernestomb/api/v2/viz/066ff802-a580-11e5-a9bb-0e3ff518bd15/viz.json",{
https:true
})
.addTo(map)
.done(function(layer) {
cartolayer = layer.getSubLayer(0);
$('#hide').click(function(){
$(".cartodb-legend.choropleth").hide();
console.log('hide button has been pressed');
})
$('#show').click(function(){
$(".cartodb-legend.choropleth").show();
console.log('show button has been pressed');
})
})
.error(function(err) {
console.log("Error: " + err);
});
}
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment