Simple script to bulk add non redundant tags on boundary=administrative ways
Posted by capiscuas on 22 April 2018 in English. Last updated on 24 April 2018.Sometimes we find in some cities/countries some boundary ways (the ones that define the political borders of provinces/towns/countries) that are missing some tag(not appearing already in the relations, because it’s better to avoid redundant data.
Example of boundary way without any tag:
For the renders and 3rd party apps that is not a big problem because that way is indide the the corresponding relations with different admin_level, it can be shared by one or many relations, but what happens if we need to add a tag to those ways based on the data from their relations?
The script is the following, based on Dmitri Lebedev’s osm2python library (not python3 compatible yet, help migrating).
# -*- coding: utf-8 -*-
# Use python2, since osm2python is not ported to python3
from osm2python.tree import load, dump
from collections import defaultdict
origin_osm_filename = 'boundaries.osm'
destiny_osm_filename = 'boundaries_updated.osm'
# loading the .osm file
osmtree = load(open(origin_osm_filename))
ways_min_admin_levels = defaultdict(int)
for i, r in osmtree.relations.items():
if 'admin_level' in r.tags:
admin_level = int(r.tags['admin_level'])
else:
print(r, 'has no admin_level')
for way in r.members:
if ways_min_admin_levels[way.ref] == 0 or ways_min_admin_levels[way.ref] > admin_level:
ways_min_admin_levels[way.ref] = admin_level
for i, w in osmtree.ways.items():
w.tags['admin_level'] = str(ways_min_admin_levels[i])
# Saving to .osm
dump(open(destiny_osm_filename, 'w'), osmtree)
The result example looks like this: As you can see the way now has admin_level=5 which is the minimum level of all the boundary relations that way is inside of.
After some comments below, I realized that adding redundant data in OSM is not a good practice so better to use the script for other cases.
I hope it is helpful for you and you can hack it to do more things than needed.