Cómo filtrar ways de OpenStreetmap por etiqueta desde archivo .osm.pbf usando Python y Osmium

En nuestro post anterior Ejemplo mínimo de cómo leer un archivo .osm.pbf usando Python y osmium investigamos cómo leer un archivo .osm.pbf y contar todos los nodos, ways y relaciones.

Hoy, investigaremos cómo filtrar ways específicos por etiqueta usando osmium trabajando en archivos .osm.pbf. En este ejemplo, filtraremos por highway: trunk

filter_ways_osmium.py
#!/usr/bin/env python3
import osmium as osm
from collections import namedtuple
import itertools

Way = namedtuple("Way", ["id", "nodes", "tags"])

class FindHighwayTrunks(osm.SimpleHandler):
    """
    Find ways con "highway: trunk" tag
    """

    def __init__(self):
        osm.SimpleHandler.__init__(self)
        self.ways = []

    def way(self, way):
        # If este way es un highway: trunk, ...
        if way.tags.get("highway") == "trunk":
            # ... add lo a self.ways
            # NOTE: No podemos keep un reference al way object,
            # so tenemos que create un new Way object
            nodes = [node.ref for node in way.nodes]
            self.ways.append(Way(way.id, nodes, dict(way.tags)))

# Find ways con el given tag
way_finder = FindHighwayTrunks()
way_finder.apply_file("kenya-latest.osm.pbf")

print(f"Found {len(way_finder.ways)} ways")

Este ejemplo usa kenya-latest.osm.pbf descargado de Geofabrik, pero puedes usar cualquier archivo .osm.pbf. Analizar dicho archivo toma aproximadamente 10 segundos en mi escritorio.

Ten en cuenta que no podemos simplemente hacer self.ways.append(way) porque way es un objeto Protobuf temporal/interno y no puede ser usado directamente después. Por lo tanto, creamos nuestro propio objeto que simplemente envuelve los contenidos extraídos del way: Su id, su lista de nodes (IDs de nodos) y un diccionario conteniendo los tags. De lo contrario, verás este mensaje de error:

osmium_runtime_error.txt
Traceback (most recent call last):
  File "run.py", line 32, in <module>
    trunk_handler.apply_file("kenya-latest.osm.pbf")
RuntimeError: Way callback keeps reference to OSM object. This is not allowed.

Echa un vistazo a artículos similares por categoría: Geografía Geoinformática OpenStreetMap Python