Skip to content

Instantly share code, notes, and snippets.

@cjhin
Last active July 24, 2016 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjhin/27e01c636dcc0bfa256c7a225971354d to your computer and use it in GitHub Desktop.
Save cjhin/27e01c636dcc0bfa256c7a225971354d to your computer and use it in GitHub Desktop.
Chicago
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.zipcode {
stroke: steelblue;
fill: #FFF;
}
</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
/*
data comes from: https://github.com/smartchicago/chicago-atlas/blob/master/db/import/zipcodes.geojson
lots of help from http://stackoverflow.com/questions/14492284/center-a-map-in-d3-given-a-geojson-object
*/
//Load in GeoJSON data
d3.json("zipcodes.json", function(json) {
//Width and height
var width = 900;
var height = 450;
// create a first guess for the projection
var center = d3.geo.centroid(json)
var scale = 150;
var projection = d3.geo.mercator().scale(scale).center(center);
//Define path generator
var path = d3.geo.path()
.projection(projection);
// using the path determine the bounds of the current map and use
// these to determine better values for the scale and translation
var bounds = path.bounds(json);
var hscale = scale * width / (bounds[1][0] - bounds[0][0]);
var vscale = scale * height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0]) / 2,
height - (bounds[0][1] + bounds[1][1]) / 2];
// new projection
projection = d3.geo.mercator().center(center)
.scale(scale * 0.9).translate(offset);
path = path.projection(projection);
//Create SVG element
var svg = d3.select(".chart")
.attr("width", width)
.attr("height", height)
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.attr("class", "zipcode");
});
</script>
<body>
<svg class="chart"></svg>
</body>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment