#!/usr/bin/python3 import argparse import json from typing import Optional from xml.etree.ElementTree import ElementTree from wrpylib.argparse_tools import bool_type from wrpylib.json_tools import format_json from wrpylib.wrgeojson import join_wrgeojson_ways, simplify_ways from wrpylib.wrosm import find_sledrun_relations, tags, convert_osm_to_geojson, DeRefError def process_osm_file(filename: str, single: Optional[int], join_ways: bool, simplify: bool): """converts an .osm file to (s). :param filename: name of the .osm file :param single: if not None, an int argument that specifies the number of the to display (1 based) :param join_ways: joins subsequent ways of same type :param simplify_max_dist: If not None, omit points to make the map file size smaller. The float value gives the number of meters of way error that is maximally accepted. """ osm_tree = ElementTree() osm_tree.parse(filename) # Search all sled run relations sledrun_list = list(find_sledrun_relations(osm_tree)) if single is not None: sledrun_list = [sledrun_list[single - 1]] for sledrun_relation in sledrun_list: # sledrun is an Element 'relation' # Make a nice title sledrun_tags = tags(sledrun_relation) title = f"{sledrun_tags.get('name')} ({sledrun_tags.get('website')}) [{sledrun_relation.get('id')}]" print(title) print("-" * len(title)) # Convert to geojson try: sledrun_geojson = convert_osm_to_geojson(osm_tree, sledrun_relation) except DeRefError: print('Error: Incomplete XML - please load larger region.') continue # Merge sledrun ways of the same type if join_ways: join_wrgeojson_ways(sledrun_geojson) # Simplify the sledrunMap if simplify: simplify_ways(sledrun_geojson) # Print result print(format_json(sledrun_geojson)) print() def main(): epilog = "Writing result to a file without encoding errors:\n" + \ "$ PYTHONIOENCODING='ISO8859-15' python osm_to_wrgeojson.py mymap.osm > mymap.json" parser = argparse.ArgumentParser(description='Converts an OpenStreetMap .osm file to wrgeojson.', epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--single', type=int, help='just display the ith (1 based) instead of all') parser.add_argument('--join-ways', type=bool_type, default=True, help='joins subsequent ways of same type (default: True)') parser.add_argument('--simplify', type=bool_type, default=False, help='simplify the map (reduce number of points in paths) (default: False)') parser.add_argument('osmfile', type=str, help='input file name (.osm file)') args = parser.parse_args() process_osm_file(args.osmfile, single=args.single, join_ways=args.join_ways, simplify=args.simplify) if __name__ == '__main__': main()