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.
-
-
Save joannecheng/8817038 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment