Skip to content

Instantly share code, notes, and snippets.

@andest01
Created March 18, 2014 15:22
Show Gist options
  • Save andest01/9622206 to your computer and use it in GitHub Desktop.
Save andest01/9622206 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Convert Shapefile (.shp) to TopoJSON, version 1
# @see http://bost.ocks.org/mike/map/
# Before running this script:
#
# brew install gdal
# npm install -g topojson
# which ogr2ogr
# which topojson
# Cleanup from last time.
rm -rf ../../json/geo
rm -rf ../../json/topo
mkdir ../../json/geo
mkdir ../../json/geo/countries
mkdir ../../json/geo/regions
mkdir ../../json/topo
mkdir ../../json/topo/countries
# # Generate the GeoJSON from the Shapefile
ogr2ogr -f GeoJSON ../../json/geo/countries.json ../shp/countries/ne_10m_admin_0_countries.shp
# Read in the GeoJSON file.
CountryFile=../../json/geo/countries.json
# Match lines that have a country code.
adm0RegExp='"ADM0_A3": "(...)"'
while read line
do
if [[ $line =~ $adm0RegExp ]]
then
countryCode=${BASH_REMATCH[1]}
countryName="$(echo $countryCode | tr '[A-Z]' '[a-z]' | tr ' ' '-')"
ogr2ogr \
-f GeoJSON \
-where "ADM0_A3 = '$countryCode'" \
../../json/geo/countries/$countryName.json \
../shp/countries/ne_10m_admin_0_countries.shp
ogr2ogr \
-f GeoJSON \
-where "adm0_a3 = '$countryCode'" \
../../json/geo/regions/$countryName.json \
../shp/states_provinces/ne_10m_admin_1_states_provinces.shp
# countryDir=../../json/geo/regions/"$countryName"
RegionFile=../../json/geo/regions/$countryName.json
nameRegExp='"name": "([A-Za-z,\.\ ]+)"'
while read line
do
if [[ $line =~ $nameRegExp ]]; then
if [ ! -d ../../json/geo/regions/"$countryName" ]; then
mkdir ../../json/geo/regions/$countryName
fi
regionCode=${BASH_REMATCH[1]}
regionName="$(echo $regionCode | tr '[A-Z]' '[a-z]' | tr ' ' '-')"
# echo "$countryName/$regionName"
if [ ! -e ../../json/geo/regions/"$countryName"/"$regionName".json ]; then
ogr2ogr \
-f GeoJSON \
-where "adm0_a3 = '$countryCode' AND name = '$regionCode'" \
../../json/geo/regions/$countryName/$regionName.json \
../shp/states_provinces/ne_10m_admin_1_states_provinces.shp
fi
fi
done <$RegionFile
if [ -d ../../json/geo/regions/"$countryName" ]; then
topojson \
--simplify-proportion=0.05 \
-o ../../json/topo/countries/$countryName.json \
-- \
../../json/geo/countries/$countryName.json \
../../json/geo/regions/$countryName/*.json
else
topojson \
--simplify-proportion=0.05 \
-o ../../json/topo/countries/$countryName.json \
-- \
../../json/geo/countries/$countryName.json
fi
fi
done <$CountryFile
topojson -o ../../json/topo/lakes.json lakes=../shp/lakes/ne_110m_lakes.shp
topojson -o ../../json/topo/land.json land=../shp/land/ne_110m_land.shp
rm -rf ../../json/geo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment