Mapping Town Boundaries with D3
I have seen a lot of cool D3 maps of US states, counties, and even zipcodes but what about cities or towns? I don’t mean plotting geo coordinates of a particular city but actually drawing the city or town boundary on the map. A population choropleth is a good use case for this but I have only seen one example of Vermont that shows town specific information. The initial problem is where do we even get the specific town boundary geospatial data?
For the world or even US states, we have free Natural Earth vectors. For zipcodes, we have some data from USPS. For counties, we have the Census data and it includes Tracts, Block Groups, and Blocks but none of this correctly translates to actual towns. Doing a search for town boundaries landed me on the MassGIS Data website which has a this geo data for New England states, so today I will go through the process of creating a D3 map for towns in a state, visualizing all New England states and their towns, and finally, animating population data over time in Massachusetts towns.
I think that finding the town data is the biggest issue but the mass.gov website has town boundaries for both Massachusetts and adjacent states. It is presented in a shapefile so the first step is to turn that over into GeoJSON. I have used the following ogr2ogr command to convert the shapefile into GeoJSON with EPSG:4326 projection:
ogr2ogr -f GeoJSON -t_srs EPSG:4326 ma.json TOWNSSURVEY_POLYM.shp
Now, for D3, I want to work with TopoJSON and it’s also an opportunity to remove many properties and add some simplification and quantization. I have used the following command to convert the GeoJSON file to TopoJSON:
topojson --id-property TOWN -q 1e3 -s 1e-8 -o ma.topo.json ma.json
You can read more about TopoJSON options here but this basically produced a TopoJSON file of Massachusetts town boundaries with the town name as the id property. This gave me enough to create a nice Map of Massachusetts with towns and tooltips. I did the same for other adjacent states:
- D3 Map of Rhode Island Towns
- D3 Map of Connecticut Towns
- D3 Map of Maine Towns
- D3 Map of Vermont Towns
- D3 Map of New Hampshire Towns
I skipped on New York and instead, created a map of New England with States and Town Boundaries. I think this is pretty cool but I wanted to make something more useful. How about visualizing population change across Massachusetts towns from 1980s to 2010? I recreated the TopoJSON for MA with the same simplification and quantization parameters, but this time I kept all the extra properties which include population data for the 4 decades. Using d3 transitions for animation, here is a nice D3 Map of Mass Towns showing population change over time.
Understanding TopoJSON quantization and simplification
The distillery, a simple GUI for TopoJSON