This is a demonstration of how to create a combination town/county map from a shapefile using TopoJSON and d3.js.
It includes a simplified version of the code used for the Massachusetts special Senate election results on The Huffington Post.
Get the data
Download a shapefile of Massachusetts towns from the state's GIS site:
Unzip the file:
Project the shapefile
ogr2ogr -f 'ESRI Shapefile' -t_srs 'EPSG:3585' towns-projected.shp census2000towns_poly.shp
Convert the shapefile to TopoJSON
We already know the dimensions we want for our map: 615x375. Since we're using a projected shapefile, we can specify the width and height when we generate the TopoJSON, and then do not have to reproject and resize the map in the browser.
We also need to know which county each town is in, so we can show a map of counties as well as towns. The shapefile doesn't have county information, though, so we need to add it. We'll do that by using an external properties file that contains a list of town IDs (which do appear in the shapefile) and the FIPS code for the town's county.
We're also going to simplify the town shapes.
topojson --width=615 --height=373 -s 10 --id-property +TOWN_ID -e county_towns.csv -p town=town,fips=fips -o ma-towns.topojson towns=towns-projected.shp
That gives us a 73K file, ma-towns.topojson. You can reduce file size further by changing the simplification threshold.
Displaying the TopoJSON
See the code below for the basics of displaying the TopoJSON file and toggling between showing towns and counties.