Monday, 24 June 2013

Converting shapefiles to TopoJSON + a GitHub secret

This blog post will show you how to convert shapefiles to TopoJSON. We'll convert the two shapefiles we created in my previous blog post, containing all counties and municipalities of Norway.

In a blog post from November last year I looked at various strategies to minify GeoJSON files. TopoJSON is an extension of GeoJSON that encodes topolog (e.g. shared borders between counties and municipalities). Polygons and lines in TopoJSON are represented by stiching together shared line segments. The shared boundary between two municipalities are represented only once, reducing the file size. Counties and municipalities are also sharing the same borders, and TileJSON are capeable of keeping both features in a single file. I won't go into detail, as the format is very well explained on this page.

Our shapefiles are using the Universal Transverse Mercator (UTM) 33N projection, a common projection for maps covering mainland Norway. If you want to keep this coordinate system in your TopoJSON file, you can just convert the shapefiles directly on the command line:

topojson --id-property NR -p name=NAVN -p name -o NO_Admin_UTM33.topojson NO_Fylker_pol.shp NO_Kommuner_pol.shp

You can download NO_Admin_UTM33.topojson on GitHub. As I want to show Norwegian counties and municipalities in various projections, I'm going to create a TopoJSON file with conventional latitude and longitude. Let's use QGIS to "unproject" our shapefiles:

  • Add the shapefiles to a project.
  • Right-click on the layer and select "Save As..."
  • Choose a new filename.
  • Click CRS Browse button and search for "EPSG:4326" (Filter). Select the CRS.
  • Press OK.

You'll find "NO_Fylker_pol_latlng.shp" and "NO_Kommuner_pol_latlng.shp" on GitHub. If you open the files in QGIS you'll see that the shape of Norway is very different:

UTM 33 vs unprojected (latitude/longitude).
Let's convert the unprojected shapefiles to TopoJSON:

topojson --id-property NR -p name=NAVN -p name -o NO_Admin_latlng.topojson NO_Fylker_pol_latlng.shp NO_Kommuner_pol_latlng.shp

Cool! I knew that GitHub recently added support for GeoJSON, but you'll get an interactive map with TopoJSON as well! Just use .topojson as the file extension. Have a look at NO_Admin_latlng.topojson on GitHub. You can also embed the map on your page like this:

In the next blog post we're start mapping with D3.js. Let the fun begin!

Nice pile of wood on Foldøy island.

No comments: