Skip to content

Instantly share code, notes, and snippets.

@niallmackenzie
Last active October 7, 2015 11: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 niallmackenzie/db53e2e8d6b9f661b26f to your computer and use it in GitHub Desktop.
Save niallmackenzie/db53e2e8d6b9f661b26f to your computer and use it in GitHub Desktop.
Project to Bounding Box Test

Trying to center a GeoJSON map in D3 by trial and error is hideous. In response to a question on Stackexchange, Mike posted a method of projecting to a GeoJSON object. It rocks. The map shows the municipality of Jönköping, part of Jönköpings Län in Sweden.

<!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="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geo.mercator()
// Create a path generator
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("jkLan.json", function(error, jkLan) {
if (error) throw error;
var kommuns = topojson.feature(jkLan, jkLan.objects.test3),
kommun = kommuns.features.filter(function(d) { return d.properties.KnKod == '0680'; })[0];
// Create a unit projection
projection
.scale(1)
.translate([0, 0]);
// Compute the bounds of a feature of interest, then derive scale & translate
var b = path.bounds(kommun),
// The first (boundary percetage) value is a great cheat to control the zoom
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
// Update the projection to use computed scale & translate
projection
.scale(s)
.translate(t);
svg.append("path")
.datum(kommuns)
.attr("class", "feature")
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(jkLan, jkLan.objects.test3, function(a, b) { return a !== b; }))
.attr("class", "mesh")
.attr("d", path);
svg.append("path")
.datum(kommun)
.attr("class", "outline")
.attr("d", path);
});
</script>
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