Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Choropleth Legend Example
<!DOCTYPE html>
<html>
<head>
<title>Custom legend with template | 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" />
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
</style>
<link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script type='html' id="legend_template">
<div class='cartodb-legend density'>
<ul>
<li class="min">
Percent %
</li>
<li class="graph leg" style="border-radius: 0; border:none">
<div class="colors">
<div class="quartile" style="background-color:#FFFFB2"></div>
<div class="quartile" style="background-color:#FECC5C"></div>
<div class="quartile" style="background-color:#FD8D3C"></div>
<div class="quartile" style="background-color:#F03B20"></div>
<div class="quartile" style="background-color:#BD0026"></div>
</div>
<div class="colors" style="font-weight:normal; text-align: center"
>
<div class="quartile" style="padding-top: 5px" >[0-20]</div>
<div class="quartile" style="padding-top: 5px" >[20-40]</div>
<div class="quartile" style="padding-top: 5px" >[40-60]</div>
<div class="quartile" style="padding-top: 5px" >[60-80]</div>
<div class="quartile" style="padding-top: 5px" >[80-100]</div>
</div>
</li>
</ul>
</div>
</script>
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>
<script>
function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [43, 0],
zoom: 3
});
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen',
}).addTo(map);
cartodb.createLayer(map, 'http://iriberri.cartodb.com/api/v2/viz/426e01ca-ecfb-11e4-9786-0e0c41326911/viz.json').addTo(map)
.done(function(layer) {
var sublayer = layer.getSubLayer(0);
var customLegend = new cdb.geo.ui.Legend({
type: "custom",
show_title: false,
title: "",
template: $('#legend_template').html(),
visible: true
});
var stackedLegend = new cdb.geo.ui.StackedLegend({
legends: [customLegend]
});
$('#map').append(stackedLegend.render().el);
})
.error(function(err) {
console.log(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