File: filter_coastlines.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 (43 lines) | stat: -rw-r--r-- 1,596 bytes parent folder | download | duplicates (3)
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
36
37
38
39
40
41
42
43
"""
Filter all objects with a coastline tag.

This example shows how to write objects to a file.

We need to go twice over the file. First read the ways, filter the ones
we are interested in and remember the nodes required. Then, in a second
run all the relevant nodes and ways are written out.
"""
import osmium
import sys


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage: python filter_coastlines.py <infile> <outfile>")
        sys.exit(-1)

    # go through the ways to find all relevant nodes
    nodes = set()
    # Pre-filter the ways by tags. The less object we need to look at, the better.
    way_filter = osmium.filter.KeyFilter('natural')
    # only scan the ways of the file
    for obj in osmium.FileProcessor(sys.argv[1], osmium.osm.WAY).with_filter(way_filter):
        if obj.tags['natural'] == 'coastline':
            nodes.update(n.ref for n in obj.nodes)

    # go through the file again and write out the data
    writer = osmium.SimpleWriter(sys.argv[2])

    # This time the pre-filtering should only apply to ways.
    way_filter = osmium.filter.KeyFilter('natural').enable_for(osmium.osm.WAY)

    # We need nodes and ways in the second pass.
    for obj in osmium.FileProcessor(sys.argv[1], osmium.osm.WAY | osmium.osm.NODE) \
                     .with_filter(way_filter):
        if obj.is_node() and obj.id in nodes:
            # Strip the object of tags along the way
            writer.add_node(obj.replace(tags={}))
        elif obj.is_way() and obj.tags['natural'] == 'coastline':
            writer.add_way(obj)

    writer.close()