Skip to content

Instantly share code, notes, and snippets.

@aaronpdennis
Forked from mbostock/.block
Last active April 3, 2017 01:48
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/eb749f44baf43066d18904750c91191c to your computer and use it in GitHub Desktop.
Save aaronpdennis/eb749f44baf43066d18904750c91191c to your computer and use it in GitHub Desktop.
Project to Bounding Box
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.feature {
fill: #ccc;
}
.mesh {
fill: none;
stroke: #fff;
stroke-width: .5px;
stroke-linejoin: round;
}
.outline {
fill: #ddd;
stroke: #000;
stroke-width: 1.5px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 1200,
height = 630;
var mapWidth = width * 0.5,
mapHeight = height;
var projection = d3.geo.conicEqualArea();
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
if (error) throw error;
var states = topojson.feature(us, us.objects.states),
state = states.features.filter(function(d) { return d.id === 25; })[0];
var b = path.bounds(state),
centroid = d3.geo.centroid(state),
pOffset = b[1][1] - b[0][1] * 0.3;
console.log(b, pOffset);
projection
.parallels([b[1][1] - pOffset, b[0][1] + pOffset])
.rotate([-1 * centroid[0]])
.scale(1)
.translate([0, 0]);
b = path.bounds(state)
var s = 0.9 / Math.max((b[1][0] - b[0][0]) / mapWidth, (b[1][1] - b[0][1]) / mapHeight),
t = [(mapWidth - s * (b[1][0] + b[0][0])) / 2, (mapHeight - s * (b[1][1] + b[0][1])) / 2];
projection
.scale(s)
.translate(t);
svg.append("path")
.datum(states)
.attr("class", "feature")
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "mesh")
.attr("d", path);
svg.append("path")
.datum(state)
.attr("class", "outline")
.attr("d", path);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment