### Install Osmread via setup.py Source: https://github.com/dezhin/osmread/blob/master/README.md Use the setup script to install the library in your environment. ```bash $ python setup.py install ``` -------------------------------- ### Representing OSM Entities Source: https://context7.com/dezhin/osmread/llms.txt Examples of Node and Way entity structures used within the osmread library. ```python # Node(id=123, version=1, changeset=456, timestamp=1609459200, uid=789, tags={'name': 'Example'}, lon=-0.12345, lat=51.54321) # Way(id=456, version=2, changeset=789, timestamp=1609459300, uid=123, tags={'highway': 'residential'}, nodes=(123, 124, 125)) ``` -------------------------------- ### Process Ways and Check for Closed Areas Source: https://context7.com/dezhin/osmread/llms.txt Parse Way elements to analyze linear features or areas. Access `id`, `tags`, and `nodes`. This example counts highways and identifies closed ways tagged as buildings. ```python from osmread import parse_file, Way # Count highways by type highway_stats = {} for entity in parse_file('region.osm.bz2'): if isinstance(entity, Way): # Access way properties way_id = entity.id # Unique OSM identifier version = entity.version # Edit version number changeset = entity.changeset # Changeset ID timestamp = entity.timestamp # Unix timestamp uid = entity.uid # User ID tags = entity.tags # Dictionary of tags nodes = entity.nodes # Tuple of node IDs forming the way # Count highway types if 'highway' in tags: highway_type = tags['highway'] highway_stats[highway_type] = highway_stats.get(highway_type, 0) + 1 # Print highway statistics print("Highway statistics:") for hw_type, count in sorted(highway_stats.items(), key=lambda x: -x[1]): print(f" {hw_type}: {count}") # Check if a way is closed (represents an area) for entity in parse_file('buildings.osm'): if isinstance(entity, Way): is_closed = len(entity.nodes) > 2 and entity.nodes[0] == entity.nodes[-1] if is_closed and 'building' in entity.tags: print(f"Building {entity.id}: {entity.tags.get('name', 'unnamed')}") ``` -------------------------------- ### Extract Nodes with Specific Tags Source: https://context7.com/dezhin/osmread/llms.txt Iterate through parsed entities to find Nodes. Access common attributes like `id`, `lat`, `lon`, and `tags`. This example filters for nodes tagged as restaurants. ```python from osmread import parse_file, Node # Extract all nodes with specific tags restaurants = [] for entity in parse_file('city.osm'): if isinstance(entity, Node): # Access node properties node_id = entity.id # Unique OSM identifier version = entity.version # Edit version number changeset = entity.changeset # Changeset ID timestamp = entity.timestamp # Unix timestamp of last edit uid = entity.uid # User ID who made the edit tags = entity.tags # Dictionary of key-value tags lon = entity.lon # Longitude coordinate lat = entity.lat # Latitude coordinate # Find restaurants if tags.get('amenity') == 'restaurant': restaurants.append({ 'id': node_id, 'name': tags.get('name', 'Unknown'), 'cuisine': tags.get('cuisine', 'Unknown'), 'coordinates': (lat, lon) }) print(f"Found {len(restaurants)} restaurants") for r in restaurants[:5]: print(f" {r['name']} ({r['cuisine']}): {r['coordinates']}") ``` -------------------------------- ### Direct PBF Parsing with PbfParser Source: https://context7.com/dezhin/osmread/llms.txt Handles Protocol Buffer Binary Format (PBF) files for more compact storage. PBF parsing in this library might be slower due to a pure Python protobuf implementation. Includes error handling for PBF-specific exceptions. ```python from osmread.parser.pbf import PbfParser from osmread import Node, Way, Relation # Create PBF parser parser = PbfParser() # Parse PBF file amenities = {} for entity in parser.parse_file('region.osm.pbf'): if isinstance(entity, (Node, Way)): amenity = entity.tags.get('amenity') if amenity: amenities[amenity] = amenities.get(amenity, 0) + 1 # Print amenity statistics print("Amenity counts:") for amenity, count in sorted(amenities.items(), key=lambda x: -x[1])[:20]: print(f" {amenity}: {count}") # Handle PBF-specific exceptions from osmread.parser.pbf import PBFException, PBFNotImplemented try: for entity in parser.parse_file('complex.osm.pbf'): process(entity) except PBFNotImplemented as e: print(f"Unsupported PBF feature: {e}") except PBFException as e: print(f"PBF parsing error: {e}") ``` -------------------------------- ### Basic CLI Element Count Source: https://context7.com/dezhin/osmread/llms.txt Counts elements in an OSM file using the command-line interface. Automatically detects compression. Supports forcing a specific format or overriding compression detection. ```bash osmread region.osm.bz2 ``` ```bash osmread data.bin -f pbf ``` ```bash osmread compressed.osm -c bz2 ``` -------------------------------- ### CLI Dump All Elements Source: https://context7.com/dezhin/osmread/llms.txt Dumps all elements from an OSM file for debugging purposes using the command-line interface. Requires the '-d' flag. ```bash osmread small_area.osm -d ``` -------------------------------- ### Direct XML Parsing with XmlParser Source: https://context7.com/dezhin/osmread/llms.txt Utilizes XmlParser for direct XML parsing, supporting compressed files. It leverages lxml if available, falling back to the standard library. Demonstrates parsing from a file path and a file object. ```python from osmread.parser.xml import XmlParser from osmread import Node, Way, Relation # Create parser with compression option parser = XmlParser(compression='bz2') # Parse file directly node_count = 0 way_count = 0 relation_count = 0 for entity in parser.parse_file('region.osm.bz2'): if isinstance(entity, Node): node_count += 1 elif isinstance(entity, Way): way_count += 1 elif isinstance(entity, Relation): relation_count += 1 print(f"Parsed {node_count} nodes, {way_count} ways, {relation_count} relations") # Parse from file object with open('small_area.osm', 'rb') as fp: parser = XmlParser() for entity in parser.parse(fp): print(f"{type(entity).__name__} {entity.id}: {entity.tags}") ``` -------------------------------- ### Parse OSM File with Osmread Source: https://context7.com/dezhin/osmread/llms.txt Use `parse_file` to read OSM data. It auto-detects format and compression. You can also force format or override compression detection. ```python from osmread import parse_file, Node, Way, Relation # Parse an OSM file (supports .osm, .xml, .osm.bz2, .xml.bz2, .osm.gz, .xml.gz, .pbf) for entity in parse_file('region.osm.bz2'): if isinstance(entity, Node): print(f"Node {entity.id}: ({entity.lat}, {entity.lon})") print(f" Tags: {entity.tags}") elif isinstance(entity, Way): print(f"Way {entity.id}: {len(entity.nodes)} nodes") print(f" Tags: {entity.tags}") elif isinstance(entity, Relation): print(f"Relation {entity.id}: {len(entity.members)} members") print(f" Tags: {entity.tags}") # Force specific format with the 'format' parameter for entity in parse_file('data.bin', format='pbf'): print(entity) # Override compression detection for entity in parse_file('compressed_data.osm', compression='bz2'): print(entity) ``` -------------------------------- ### Parse OpenStreetMap files Source: https://github.com/dezhin/osmread/blob/master/README.md Iterate through entities in an OSM file and filter by type and tags. ```python from osmread import parse_file, Way highway_count = 0 for entity in parse_file('foo.osm.bz2'): if isinstance(entity, Way) and 'highway' in entity.tags: highway_count += 1 print("%d highways found" % highway_count) ``` -------------------------------- ### parse_file Source: https://context7.com/dezhin/osmread/llms.txt The primary entry point for reading OSM data. It automatically detects file formats and compression, returning a generator of OSM entities. ```APIDOC ## parse_file(filename, format=None, compression=None) ### Description Reads an OpenStreetMap data file and yields Node, Way, and Relation objects. Automatically detects format and compression unless overridden. ### Parameters #### Arguments - **filename** (str) - Required - Path to the OSM file. - **format** (str) - Optional - Force a specific format ('xml' or 'pbf'). - **compression** (str) - Optional - Force a specific compression ('bz2' or 'gz'). ### Response - **generator** (iterator) - Yields Node, Way, or Relation objects. ``` -------------------------------- ### Parse and Analyze Bus Route Relations Source: https://context7.com/dezhin/osmread/llms.txt Iterates through OSM entities to find and analyze 'route=bus' relations, extracting route details and member information. Requires importing necessary classes from osmread. ```python from osmread import parse_file, Relation, Node, Way, RelationMember # Find and analyze route relations bus_routes = [] for entity in parse_file('city.osm'): if isinstance(entity, Relation): # Access relation properties rel_id = entity.id # Unique OSM identifier version = entity.version # Edit version number changeset = entity.changeset # Changeset ID timestamp = entity.timestamp # Unix timestamp uid = entity.uid # User ID tags = entity.tags # Dictionary of tags members = entity.members # Tuple of RelationMember namedtuples # Find bus routes if tags.get('type') == 'route' and tags.get('route') == 'bus': stops = [] route_ways = [] for member in members: # RelationMember has: role, type (Node/Way/Relation class), member_id role = member.role # String: 'stop', 'platform', 'forward', etc. member_type = member.type # Class: Node, Way, or Relation member_id = member.member_id # OSM ID of the referenced element if member_type == Node and role in ('stop', 'platform'): stops.append(member_id) elif member_type == Way: route_ways.append(member_id) bus_routes.append({ 'id': rel_id, 'ref': tags.get('ref', 'N/A'), 'name': tags.get('name', 'Unknown'), 'stops': len(stops), 'ways': len(route_ways) }) print(f"Found {len(bus_routes)} bus routes") for route in bus_routes[:5]: print(f" Line {route['ref']}: {route['name']} ({route['stops']} stops)") ``` -------------------------------- ### Node Element Source: https://context7.com/dezhin/osmread/llms.txt Represents a point on the map with geographic coordinates and metadata. ```APIDOC ## Node Object ### Description Represents a geographic point. Contains standard OSM metadata and coordinate information. ### Attributes - **id** (int) - Unique OSM identifier. - **version** (int) - Edit version number. - **changeset** (int) - Changeset ID. - **timestamp** (int) - Unix timestamp of last edit. - **uid** (int) - User ID of the editor. - **tags** (dict) - Key-value pairs of tags. - **lon** (float) - Longitude coordinate. - **lat** (float) - Latitude coordinate. ``` -------------------------------- ### Way Element Source: https://context7.com/dezhin/osmread/llms.txt Represents a linear feature or area boundary defined by an ordered list of nodes. ```APIDOC ## Way Object ### Description Represents a linear feature (road, river) or area boundary. Composed of an ordered list of node references. ### Attributes - **id** (int) - Unique OSM identifier. - **version** (int) - Edit version number. - **changeset** (int) - Changeset ID. - **timestamp** (int) - Unix timestamp. - **uid** (int) - User ID. - **tags** (dict) - Key-value pairs of tags. - **nodes** (tuple) - Ordered list of node IDs forming the way. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.