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.
Download a shapefile of Massachusetts towns from the state’s GIS site:
wget http://wsgw.mass.gov/data/gispub/shape/census2000/towns/census2000towns_poly.exe
Unzip the file:
unzip census2000towns_poly.exe
We then create a new shapefile with projected coordinates, using an appropriate projection for Massachusetts. Read more here about projected TopoJSON
ogr2ogr -f 'ESRI Shapefile' -t_srs 'EPSG:3585' towns-projected.shp census2000towns_poly.shp
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.
See the code below for the basics of displaying the TopoJSON file and toggling between showing towns and counties.