Skip to content

Instantly share code, notes, and snippets.

@almccon
Forked from mbostock/.block
Last active June 15, 2016 18:18
Show Gist options
  • Save almccon/fb125b016b5c9afad99b to your computer and use it in GitHub Desktop.
Save almccon/fb125b016b5c9afad99b to your computer and use it in GitHub Desktop.
Merging TopoJSON states

This demonstrates using topojson.merge, a new feature in TopoJSON 1.6, to merge multiple polygons into a single polygon whilst removing interior borders. (An alternative approach is to draw the polygons twice.)

Unlike mbostock's original example, this uses a pre-projected topojson file and a null projection.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.state {
fill: #ccc;
}
.state-boundary {
fill: none;
stroke: #fff;
}
.state.selected {
fill: orange;
stroke: #000;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 1024,
height = 768;
var path = d3.geo.path()
.projection(null); // topojson file is already projected
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var selected = d3.set([
'AK', 'YT', 'BC', 'WA', 'OR', 'CA'
]);
d3.json("/almccon/raw/fb125b016b5c9afad99b/ne_50m_usa_canada.topojson", function(error, us) {
console.log(us);
svg.append("path")
.datum(topojson.feature(us, us.objects.usa_canada))
.attr("class", "state")
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(us, us.objects.usa_canada, function(a, b) { return a !== b; }))
.attr("class", "state-boundary")
.attr("d", path);
svg.append("path")
.datum(topojson.merge(us, us.objects.usa_canada.geometries.filter(function(d) { return selected.has(d.id); })))
.attr("class", "state selected")
.attr("d", path);
});
d3.select(self.frameElement).style("height", height + "px");
</script>
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment