Skip to content

Instantly share code, notes, and snippets.

@Robsteranium
Last active March 9, 2021 19:48
Show Gist options
  • Save Robsteranium/df5e3b42e05f446b718a to your computer and use it in GitHub Desktop.
Save Robsteranium/df5e3b42e05f446b718a to your computer and use it in GitHub Desktop.
Convert ONS Shapefiles to GeoJSON

This gist describes how to create GeoJSON polygons from UK statistical boundaries for use in choropleths.

  1. Download the boundaries you're interested in from the ONS's Open Geography Portal:

    wget https://geoportal.statistics.gov.uk/Docs/Boundaries/Clinical_commissioning_groups_\(Eng\)_Apr_2013_Boundaries_\(Generalised_Clipped\).zip -O ccg-2013.zip
    unzip ccg-2013.zip -d shapes
    
  2. Re-project this from UK Grid Reference Eastings and Northings into Latitude and Longitude coordinates (i.e. EPSG:4326 aka WGS 84). You can use GDAL to do this:

    ogr2ogr -f 'ESRI Shapefile' epsg shapes/CCG_APR_2013_EN_BGC.shp -t_srs EPSG:4326

  3. Simplify the polygons (to make your map load and render more quickly) using a tool that keeps the topography intact (i.e. that will simplify the boundaries together - if we did them one by one leads we would be left with holes and intersections). Mapshaper is great:

    mkdir boundaries
    mapshaper -i encoding=ISO88591 epsg/CCG_APR_2013_EN_BGC.shp -simplify 5% -o format=geojson boundaries/all.json
    
  4. Split the polygons into a single file per boundary so that they can be served and styled separately. It's stretching it to call this a ruby one-liner but it will do the trick. Note that you'll need to specify the key name of the gss code (e.g. "CCG13CD"):

    ruby -rjson -e 'JSON.parse(ARGF.read)["features"].each{|feature| File.open("boundaries/"+feature["properties"]["CCG13CD"]+".json","w") {|f| f.write(feature.to_json)}}' < boundaries/all.json
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment