PyOsmium

4.3.1 · active · verified Fri Apr 17

PyOsmium provides Python bindings for libosmium, a high-performance C++ library designed for processing OpenStreetMap (OSM) data. It enables efficient reading, writing, and manipulation of various OSM file formats (PBF, XML, O5M) and change files, making it suitable for large-scale geospatial data tasks. The library is actively maintained with regular updates, typically aligning with new libosmium releases, and is currently at version 4.3.1.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `osmium.SimpleHandler` to process an OSM PBF file. It creates a temporary dummy PBF file, then defines a handler to count nodes, ways, and relations, and applies it to the file. This pattern is fundamental for reading and iterating over OSM data.

import osmium
import osmium.osm
import tempfile
import os
from datetime import datetime

# Create a dummy PBF file for demonstration purposes
# In a real scenario, you'd process an existing .osm.pbf file.
temp_pbf_file = os.path.join(tempfile.gettempdir(), "test.osm.pbf")
writer = osmium.SimpleWriter(temp_pbf_file)
writer.add_node(osmium.osm.Node(1, location=osmium.osm.Location(1.0, 1.0), user='test_user', timestamp=datetime.now()))
writer.add_node(osmium.osm.Node(2, location=osmium.osm.Location(2.0, 2.0), user='test_user', timestamp=datetime.now()))
writer.add_way(osmium.osm.Way(3, nodes=[1, 2], user='test_user', timestamp=datetime.now()))
writer.add_relation(osmium.osm.Relation(4, user='test_user', timestamp=datetime.now()))
writer.close()

class ElementCounter(osmium.SimpleHandler):
    def __init__(self):
        super().__init__()
        self.nodes = 0
        self.ways = 0
        self.relations = 0

    def node(self, n):
        self.nodes += 1

    def way(self, w):
        self.ways += 1

    def relation(self, r):
        self.relations += 1

try:
    # Process the (dummy) PBF file using the handler
    handler = ElementCounter()
    handler.apply_file(temp_pbf_file)

    print(f"Nodes: {handler.nodes}")
    print(f"Ways: {handler.ways}")
    print(f"Relations: {handler.relations}")
finally:
    # Clean up the temporary file
    if os.path.exists(temp_pbf_file):
        os.remove(temp_pbf_file)

view raw JSON →