Aapeli Vuorinen

Rendering a basic OpenStreetMap image on Ubuntu 20.04

I’ve been playing around with OSM data lately, and it’s really quite difficult to get started with it. Here’s a bash script that you can drop on a fresh AWS EC2 instance running Ubuntu 20.04 and you should end up with an image.png in your home folder after about 20 minutes, showing a nice little map of NYC.

You can choose any data source (just download an .osm.pbf formatted file into the home directory), but here I’m getting an Interline OSM extract for New York. To run this script verbatim, you need to get an API key from them and paste it below.

# Your interline token
export TOKEN="..."
export BOUNDS="(-74.11754608154298,40.69599751931472,-73.85696411132814,40.84450145446744)"

# Download OSM data extract
wget -O data.osm.pbf "https://app.interline.io/osm_extracts/download_latest?string_id=new-york_new-york&data_format=pbf&api_token=$TOKEN"

# Install postgres 13 with postgis 3
curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" |sudo tee  /etc/apt/sources.list.d/pgdg.list
sudo apt-get update
sudo apt-get install -y postgresql-13-postgis-3 osm2pgsql
sudo -u postgres createuser -s ubuntu
createdb gis
psql -d gis -c "CREATE EXTENSION postgis; CREATE EXTENSION hstore;"

# Install node, npm, and carto
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo npm install -g carto

# Clone openstreetmap-carto
git clone https://github.com/gravitystorm/openstreetmap-carto.git # b10aef3

# Load the data into postgis
osm2pgsql -G --hstore --style openstreetmap-carto/openstreetmap-carto.style --tag-transform-script openstreetmap-carto/openstreetmap-carto.lua -d gis data.osm.pbf

# Download the map style and create an xml file for mapnik
pushd openstreetmap-carto/
carto project.mml > osm.xml
# Download some extra data (mainly shapefiles) for the map style
sudo apt-get install -y python3-psycopg2 gdal-bin
./scripts/get-external-data.py
popd

# Install mapnik and openstreetmap-carto style font dependencies
sudo apt-get install -y python3-mapnik
sudo apt-get install -y fonts-noto-cjk fonts-noto-hinted fonts-noto-unhinted fonts-hanazono ttf-unifont

wget https://raw.githubusercontent.com/openstreetmap/mapnik-stylesheets/master/generate_image.py # 236f8d0

sed -i "s/bounds = (-6.5, 49.5, 2.1, 59)/bounds = $BOUNDS/g" generate_image.py
MAPNIK_MAP_FILE=openstreetmap-carto/osm.xml python3 generate_image.py