Skip to content

Instantly share code, notes, and snippets.

@aaronpdennis
Created October 4, 2017 17:07
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 aaronpdennis/cce3344e0635609c3df86fcc162cbf2b to your computer and use it in GitHub Desktop.
Save aaronpdennis/cce3344e0635609c3df86fcc162cbf2b to your computer and use it in GitHub Desktop.
Automatically define an Albers D3.js projection for a GeoJSON feature.
function framedProjection(feature, mapWidth, mapHeight) {
var projection = d3.geoAlbers();
var centroid = d3.geoCentroid(feature);
projection.rotate([-1 * centroid[0]]).scale(1).translate([0, 0]);
var path = d3.geoPath().projection(projection);
var bounds = path.bounds(feature);
var scale = 0.618 / Math.max(
(bounds[1][0] - bounds[0][0]) / mapWidth,
(bounds[1][1] - bounds[0][1]) / mapHeight
);
var translate = [
(mapWidth - scale * (bounds[1][0] + bounds[0][0])) / 2,
(mapHeight - scale * (bounds[1][1] + bounds[0][1])) / 2
];
projection.scale(scale).translate(translate);
return projection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment