A quick example showing how to find and draw adjacent areas from a topojson file.
Neighbourhoods/ neighborhoods, whatever
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>topojson neighbourhood</title> | |
<style> | |
body{ | |
font-family: sans-serif; | |
} | |
svg{ | |
border:1px solid #000; | |
} | |
path { | |
fill: #FFF; | |
stroke: #000; | |
stroke-linejoin: round; | |
} | |
#in .selected{ | |
fill:#0FF; | |
} | |
#out .selected{ | |
fill:#0FF; | |
} | |
#in path:hover{ | |
fill:#F0F; | |
cursor: pointer; | |
} | |
.vis{ | |
display:inline-block; | |
margin-right: 50px; | |
} | |
</style> | |
<body> | |
<div id="in" class="vis"> | |
<h2>Select a constituency</h2> | |
</div> | |
<div id="out" class="vis"> | |
<h2>See its neighbourhood</h2> | |
</div> | |
</body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://d3js.org/topojson.v1.min.js"></script> | |
<script> | |
var width = 300, | |
height = 300, | |
neighbors = [], | |
wales; | |
var projection = d3.geo.albers() | |
.center([-3.5, 52.54]) | |
.rotate([0, 0]) | |
.parallels([50, 60]) | |
.scale(6000) | |
.translate([width / 2, height / 2]); | |
var path = d3.geo.path() | |
.projection(projection); | |
var svgIn = d3.select("#in").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var svgOut = d3.select("#out").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
d3.json('wales.topojson', ready); | |
function drawNeighbours(index){ | |
var neighborhood = neighbors[index]; | |
var subset = topojson.feature(wales, wales.objects.constituencies).features //create a subset of the features baed on a neighbourhood list | |
.filter(function(d,i){ | |
return (neighborhood.indexOf(i) > -1) || index == i; | |
}); | |
svgOut.select("g").remove(); | |
svgOut.append("g") | |
.attr("class", "counties") | |
.selectAll("path") | |
.data(subset) | |
.enter() | |
.append("path") | |
.attr({ | |
"d":path, | |
'id':function(d){return 'sub-'+d.id;} | |
}); | |
} | |
function highlight(id){ //highlight all pats for a given constituency ID | |
d3.selectAll('path') | |
.classed('selected',function(d){ | |
return d.id == id; | |
}); | |
} | |
function ready(error, walestopo) { | |
wales = walestopo; //assign the topology to a global var for convenience | |
neighbors = topojson.neighbors(wales.objects.constituencies.geometries); //get the lists of neighbours | |
svgIn.append("g") | |
.attr("class", "counties") | |
.selectAll("path") | |
.data(topojson.feature(wales, wales.objects.constituencies).features) | |
.enter().append("path") | |
.attr({ | |
"d":path, | |
'id':function(d){return d.id;} | |
}) | |
.on("click",function(d,i){ | |
drawNeighbours(i); | |
highlight(d.id); | |
}); | |
} | |
</script> |