Skip to content

Instantly share code, notes, and snippets.

@martgnz
Last active October 28, 2017 15:55
Show Gist options
  • Save martgnz/5d463feffb0f7367b3f2 to your computer and use it in GitHub Desktop.
Save martgnz/5d463feffb0f7367b3f2 to your computer and use it in GitHub Desktop.
Spam.js Choropleth I
license: mit
height: 650
border: none

This is a simple example of a zoomable choropleth made with spam.js.

It encodes birth rates from 2014 in Barcelona census tracts.

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<meta charset="utf-8" />
<style>
canvas {
cursor: pointer;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="https://unpkg.com/rbush@1.4.3/rbush.js"></script>
<script src="https://unpkg.com/spamjs@1.1.0/spam.min.js"></script>
<script type='text/javascript'>
var hover = null;
var color = d3.scale
.threshold()
.domain([6.03, 8.63, 11.28, 16.66, 23.59])
.range(["#f0f9e8", "#ccebc5", "#a8ddb5", "#7bccc4", "#43a2ca", "#0868ac"]);
d3.json("bcn.json", function(error, d) {
topojson.presimplify(d);
var map = new ZoomableCanvasMap({
element: "body",
zoomScaleFactor: 0.3,
projection: d3.geo
.mercator()
.center([29.6, 30.47])
.scale(250000)
.rotate([0, 0, -37.6]),
width: 960,
height: 650,
data: [
{
features: topojson.feature(d, d.objects["seccio-censal"]),
static: {
paintfeature: function(parameters, d) {
parameters.context.fillStyle = color(d.properties.rate);
parameters.context.fill();
}
},
dynamic: {
postpaint: function(parameters) {
if (!hover) return;
parameters.context.beginPath();
parameters.context.lineWidth = 1 / parameters.scale;
parameters.path(hover);
parameters.context.stroke();
}
},
events: {
hover: function(parameters, d) {
hover = d;
parameters.map.paint();
},
click: function(parameters, d) {
parameters.map.zoom(d);
}
}
}
]
});
map.init();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment