Skip to content

Instantly share code, notes, and snippets.

@bycoffe
Created February 9, 2016 14:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bycoffe/e32cc94b26df9c5e28aa to your computer and use it in GitHub Desktop.
Save bycoffe/e32cc94b26df9c5e28aa to your computer and use it in GitHub Desktop.
Town/county switch with topojson
<!DOCTYPE html>
<meta charset="utf-8">
<style>
#map path {
fill: #fff;
stroke: #999;
stroke-width; 1;
}
#map path.state.border {
fill: none;
stroke-width: 2;
stroke: #333;
}
#map path.county.border {
fill: none;
stroke-width: 2;
stroke: #666;
}
</style>
<body>
<div id="map"></div>
</body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.js"></script>
<script>
d3.json("nh-towns.json", function(err, topo) {
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 500,
height = 590,
path = d3.geo.path().projection(null),
svg = d3.select("#map").append("svg").attr({
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom,
})
g = svg.append("g").attr({
transform: "translate(" + margin.left + "," + margin.top + ")scale(.83)"
}),
town = g.selectAll("path.town")
.data(topojson.feature(topo, topo.objects.counties).features)
.enter().append("path")
.attr({
"class": "town border",
d: path
})
.style({
opacity: 1
}),
countyBorder = g.append("path")
.datum(topojson.mesh(topo, topo.objects.counties, function(a, b) {
return String("000" + a.properties.fips).slice(-6).slice(0, 3) !== String("000" + b.properties.fips).slice(-6).slice(0, 3);
}))
.attr({
"class": "county border",
d: path
})
.style({
opacity: 0
})
stateBorder = g.append("path")
.datum(topojson.mesh(topo, topo.objects.counties, function(a, b) {
return a === b;
}))
.attr({
"class": "state border",
d: path
});
var selected = "town";
function toggle() {
town.transition()
.duration(1000)
.style({
opacity: selected === "town" ? .1 : 1
});
countyBorder.transition()
.duration(1000)
.style({
opacity: selected === "town" ? 1 : .1
});
selected = selected === "town" ? "county" : "town";
window.setTimeout(toggle, 1500);
}
toggle();
});
</script>
Display the source blob
Display the rendered blob
Raw
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