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