Skip to content

Instantly share code, notes, and snippets.

@joannecheng
Forked from mbostock/.block
Last active May 19, 2016 11:35
Show Gist options
  • Save joannecheng/8817038 to your computer and use it in GitHub Desktop.
Save joannecheng/8817038 to your computer and use it in GitHub Desktop.

This example uses topojson.neighbors to compute neighboring congressional districts (from the 113th congress) from geographic boundaries by detecting shared edges (arcs). The red district is the hovered district, and the orange district is the neighboring districts.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.districts {
fill: #bbb;
}
.district-boundaries {
pointer-events: none;
fill: none;
stroke: #fff;
stroke-width: .5px;
stroke-linejoin: round;
}
.districts :hover {
fill: red;
}
.neighbor {
fill: orange;
}
</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 = 960,
height = 500;
var path = d3.geo.path();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("/d/8817038/us-congress-113-with-names.json", function(error, congress) {
var districts = congress.objects['113-congress'],
neighbors = topojson.neighbors(districts.geometries);
var district = svg.append("g")
.attr("class", "districts")
.selectAll("path")
.data(topojson.feature(congress, districts).features)
.enter().append("path")
.attr("d", path);
district.append("title")
.text(function(d) { return d.id; });
district
.each(function(d, i) { d.neighbors = d3.selectAll(neighbors[i].map(function(j) { return district[0][j]; })); })
.on("mouseover", function(d) {
d3.select('#district_label').text(d.properties.name + " state id: " + d.properties.stateid);
d3.select('#district_label')
.append('ul')
.selectAll('li.neighbor')
.data(d.neighbors[0]).enter()
.append('li')
.classed('neighbor', true)
.text(function(d1) {
return d1.__data__.properties.name + " state id: " + d1.__data__.properties.stateid;
});
d.neighbors.classed("neighbor", true);
})
.on("mouseout", function(d) { d.neighbors.classed("neighbor", false); });
svg.append("path")
.attr("class", "district-boundaries")
.datum(topojson.mesh(congress, districts, function(a, b) { return a !== b; }))
.attr("d", path);
});
</script>
<div id="district_label">
</div>
</body>
</html>
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