Skip to content

Instantly share code, notes, and snippets.

Last active April 20, 2019 01:44
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Neighboring Congressional Districts
license: gpl-3.0

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">
path {
stroke-linejoin: round;
stroke-linecap: round;
.land {
fill: #bbb;
.land :hover {
fill: red;
.land .neighbor {
fill: orange;
.border {
pointer-events: none;
fill: none;
stroke: #fff;
.border--district {
stroke-width: .5px;
.border--state {
stroke-width: 1.5px;
<script src="//"></script>
<script src="//"></script>
<script src="//"></script>
var width = 960,
height = 600;
var projection = d3.geo.albersUsa()
.translate([width / 2, height / 2]);
var path = d3.geo.path()
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
.defer(d3.json, "/mbostock/raw/4090846/us.json")
.defer(d3.json, "/mbostock/raw/4090846/us-congress-113.json")
function ready(error, us, congress) {
if (error) throw error;
var districts = congress.objects.districts,
neighbors = topojson.neighbors(districts.geometries);
.attr("id", "land")
.attr("d", path);
.attr("id", "clip-land")
.attr("xlink:href", "#land");
var district = svg.append("g")
.attr("class", "land")
.attr("clip-path", "url(#clip-land)")
.data(topojson.feature(congress, districts).features)
.attr("d", path);
.text(function(d) { return; });
.each(function(d, i) { d.neighbors = d3.selectAll(neighbors[i].map(function(j) { return district[0][j]; })); })
.on("mouseover", function(d) { d.neighbors.classed("neighbor", true); })
.on("mouseout", function(d) { d.neighbors.classed("neighbor", false); });
.attr("class", "border border--district")
.datum(topojson.mesh(congress, congress.objects.districts, function(a, b) { return a !== b && ( / 1000 | 0) === ( / 1000 | 0); }))
.attr("d", path);
.attr("class", "border border--state")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("d", path);
}"height", height + "px");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment