4 from typing import Optional
5 from xml.etree.ElementTree import ElementTree
7 from wrpylib.argparse_tools import bool_type
8 from wrpylib.json_tools import format_json
9 from wrpylib.wrgeojson import join_wrgeojson_ways, simplify_ways
10 from wrpylib.wrosm import find_sledrun_relations, tags, convert_osm_to_geojson, DeRefError
13 def process_osm_file(filename: str, single: Optional[int], join_ways: bool, simplify: bool):
14 """converts an .osm file to <wrmap>(s).
16 :param filename: name of the .osm file
17 :param single: if not None, an int argument that specifies the number of the <wrmap> to display (1 based)
18 :param join_ways: joins subsequent ways of same type
19 :param simplify_max_dist: If not None, omit points to make the map file size smaller.
20 The float value gives the number of meters of way error that is maximally accepted.
22 osm_tree = ElementTree()
23 osm_tree.parse(filename)
25 # Search all sled run relations
26 sledrun_list = list(find_sledrun_relations(osm_tree))
27 if single is not None:
28 sledrun_list = [sledrun_list[single - 1]]
30 for sledrun_relation in sledrun_list: # sledrun is an Element 'relation'
32 sledrun_tags = tags(sledrun_relation)
33 title = f"{sledrun_tags.get('name')} ({sledrun_tags.get('website')}) [{sledrun_relation.get('id')}]"
35 print("-" * len(title))
39 sledrun_geojson = convert_osm_to_geojson(osm_tree, sledrun_relation)
41 print('Error: Incomplete XML - please load larger region.')
44 # Merge sledrun ways of the same type
46 join_wrgeojson_ways(sledrun_geojson)
48 # Simplify the sledrunMap
50 simplify_ways(sledrun_geojson)
53 print(format_json(sledrun_geojson))
58 epilog = "Writing result to a file without encoding errors:\n" + \
59 "$ PYTHONIOENCODING='ISO8859-15' python osm_to_wrgeojson.py mymap.osm > mymap.json"
60 parser = argparse.ArgumentParser(description='Converts an OpenStreetMap .osm file to wrgeojson.',
61 epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
62 parser.add_argument('--single', type=int, help='just display the ith (1 based) <wrmap> instead of all')
63 parser.add_argument('--join-ways', type=bool_type, default=True,
64 help='joins subsequent ways of same type (default: True)')
65 parser.add_argument('--simplify', type=bool_type, default=False,
66 help='simplify the map (reduce number of points in paths) (default: False)')
67 parser.add_argument('osmfile', type=str, help='input file name (.osm file)')
68 args = parser.parse_args()
70 process_osm_file(args.osmfile, single=args.single, join_ways=args.join_ways, simplify=args.simplify)
73 if __name__ == '__main__':