File: road_length.py

package info (click to toggle)
pyosmium 4.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,584 kB
  • sloc: python: 4,400; cpp: 2,504; makefile: 20
file content (35 lines) | stat: -rw-r--r-- 1,098 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Compute the total length of highways in an osm file.

Shows how to extract the geometry of a way.
"""
import osmium
import sys


def main(osmfile):
    total = 0.0
    # As we need the way geometry, the node locations need to be cached.
    # This is enabled with the with_locations() function.
    for obj in osmium.FileProcessor(osmfile, osmium.osm.NODE | osmium.osm.WAY)\
                     .with_locations()\
                     .with_filter(osmium.filter.KeyFilter('highway')):
        if obj.is_way():
            try:
                total += osmium.geom.haversine_distance(obj.nodes)
            except osmium.InvalidLocationError:
                # A location error might occur if the osm file is an extract
                # where nodes of ways near the boundary are missing.
                print("WARNING: way %d incomplete. Ignoring." % obj.id)

    print('Total way length: %.2f km' % (total/1000))

    return 0


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python %s <osmfile>" % sys.argv[0])
        sys.exit(-1)

    exit(main(sys.argv[1]))