Skip to content

Instantly share code, notes, and snippets.

@AlexandraKapp
Created July 11, 2023 07:39
Show Gist options
  • Save AlexandraKapp/c95ef03f380530f8233fbf7c3235d284 to your computer and use it in GitHub Desktop.
Save AlexandraKapp/c95ef03f380530f8233fbf7c3235d284 to your computer and use it in GitHub Desktop.

How to add / edit an attribute in a OpenStreetMap (OSM) PBF file

OSM2psql is a handy tool for importing OSM data into a PostgreSQL database. Though, the created database cannot be converted back to a PBF file. For example, to use a routing algorithm (e.g., Graphhopper) with a custom weighting, the PBF format is needed. For this, I used Osmosis.

For the task of editing a PBF file and re-creating a new PBF file I used the following process:

1. Install PostgreSQL, PostGIS and Osmosis.

For Mac, Homebrew can be used:

brew install postgresql   
brew install postgis  
brew install osmosis
brew services start postgresql@14

2. Create a database

createdb myOsmDB  #(in command line - not psql shell!)

3. Download the needed PBF file

Geofabrik provides a great free download service for OSM PBF files.

Use osmosis to import the PBF file into your database

The following steps are also described in the Osmosis PostGIS Setup description

4. Download osmosis setup script

5. Setup your database

psql -d myOsmDB 'CREATE EXTENSION postgis; CREATE EXTENSION hstore;'
psql -d myOsmDB -f osmosis-0.48.3/script/pgsnapshot_schema_0.6.sql
osmosis --read-pbf YOUR_PBF_FILE_NAME.osm.pbf --log-progress --write-pgsql database=myOsmDB 

6. make changes to your database

Using SQL (for example via a user interface like Dbeaver), edit the database as needed. All OSM tags are stored in a single column 'tags' using the hstore datatype.

-- create a new custom attribute
alter table ways
add column myNewAttribute numeric;

-- set attribute values as needed

-- store attribute in the osm hstore tag list
update ways 
set tags = tags || hstore('myNewAttribute', myNewAttribute::text)
where tags -> 'highway' <> ''; -- for example, update all ways that are highways, 
                               -- i.e., the tag highway is not empty


-- drop custom column afterwards, as it is not needed anymore
alter table ways
drop column myNewAttribute;

7. export database as PBF file

osmosis --read-pgsql database=myOsmDB --dataset-dump  --write-pbf file=YOUR_CUSTOM_PBF_FILE_NAME.osm.pbf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment