This commit is contained in:
Pim Kunis 2023-08-27 13:28:43 +02:00
parent 966ee378a2
commit 8f5fc80fd4
3 changed files with 81 additions and 57 deletions

View file

@ -1,27 +1,26 @@
#!/bin/python3 #!/bin/python3
import argparse
import osmapi import osmapi
import shapely import shapely
import pickle import pickle
from os.path import exists
OSM_KOGGENLAND_ID = 161930
PICKLE_FILE = 'polygon.pickle'
def chunks(lst, n): def chunks(lst, n):
"""Yield successive n-sized chunks from lst.""" """Yield successive n-sized chunks from lst.
https://stackoverflow.com/a/312464
CC BY-SA 4.0
"""
for i in range(0, len(lst), n): for i in range(0, len(lst), n):
yield lst[i:i + n] yield lst[i:i + n]
def dump_polygon(): def get_shell_ids(osm_api, ways):
osm_api = osmapi.OsmApi() """
koggenland = osm_api.RelationGet(OSM_KOGGENLAND_ID) Get a list of OSM node IDs
ways = filter(lambda x: x['type'] == 'way', koggenland['member']) that forms the shell of the area's polygon.
shell_ids = [] """
shell_ids = list()
for way in ways: for way in ways:
way = osm_api.WayGet(way['ref']) way = osm_api.WayGet(way['ref'])
node_ids = way['nd'] node_ids = way['nd']
@ -30,35 +29,52 @@ def dump_polygon():
for node_id in node_ids[1:]: for node_id in node_ids[1:]:
shell_ids.append(node_id) shell_ids.append(node_id)
return shell_ids
def get_node_data(osm_api, shell_ids):
"""Get the data of OSM nodes as a dict of (id -> data)."""
node_data = dict() node_data = dict()
for chunk in chunks(shell_ids, 100): for chunk in chunks(shell_ids, 100):
node_data |= osm_api.NodesGet(chunk) node_data |= osm_api.NodesGet(chunk)
return node_data
def get_shell(shell_ids, node_data):
"""Get the shell of the area's polygon as a list of (lat, lon) tuples."""
shell = list() shell = list()
for shell_id in shell_ids: for shell_id in shell_ids:
node = node_data[shell_id] node = node_data[shell_id]
shell.append((node['lat'], node['lon'])) shell.append((node['lat'], node['lon']))
koggenland_polygon = shapely.Polygon(shell) return shell
with open(PICKLE_FILE, 'wb') as f:
pickle.dump(koggenland_polygon, f)
def main(): def main(args):
if not exists(PICKLE_FILE): osm_api = osmapi.OsmApi()
print('Using OSM API to create polygon...') rel = osm_api.RelationGet(args.osm_relation_id)
dump_polygon() # Filter out city centre etc.
print('Dumped polygon to file.') ways = filter(lambda x: x['type'] == 'way', rel['member'])
with open(PICKLE_FILE, 'rb') as f: shell_ids = get_shell_ids(osm_api, ways)
area = pickle.load(f) node_data = get_node_data(osm_api, shell_ids)
print('Loaded polygon from file.') shell = get_shell(shell_ids, node_data)
polygon = shapely.Polygon(shell)
point_out = shapely.Point(52.68811, 4.91267) with open(args.output_file, 'wb') as f:
point_in = shapely.Point(52.69168, 4.91324) pickle.dump(polygon, f)
print('out', area.contains(point_out))
print('in', area.contains(point_in))
if __name__ == '__main__': if __name__ == '__main__':
main() parser = argparse.ArgumentParser(description="""
Creates a polygon from an OpenStreetMap relation and saves this
to a file as a Python pickle.
""")
parser.add_argument("osm-relation-id",
help="OpenStreetMap relation ID", type=int)
parser.add_argument(
"-v", "--output-file", help="Output file for the resulting polygon",
default="polygon.pickle")
args = parser.parse_args()
main(args)

36
gc_area.py Executable file
View file

@ -0,0 +1,36 @@
#!/bin/python3
import argparse
import gpxpy
import gpxpy.gpx
import shapely
import pickle
def main(args):
with open(args.polygon_file, 'rb') as f:
area = pickle.load(f)
with open(args.input_file, 'rb') as f:
gpx = gpxpy.parse(f)
gpx.waypoints = list(filter(lambda wp: area.contains(
shapely.Point(wp.latitude, wp.longitude)), gpx.waypoints))
with open(args.output_file, 'w') as f:
f.write(gpx.to_xml())
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""
Takes an input GPX file containing
geocaches and filters out any waypoints outside a given area.
""")
parser.add_argument("input-file", help="Input GPX file")
parser.add_argument("output-file", help="Output GPX file")
parser.add_argument(
"-p", "--polygon-file", help="File containing area's polygon",
default="polygon.pickle")
args = parser.parse_args()
main(args)

View file

@ -1,28 +0,0 @@
#!/bin/python3
import gpxpy
import gpxpy.gpx
import shapely
import pickle
GPX_IN_FILE = 'caches.gpx'
GPX_OUT_FILE = 'koggenland.gpx'
PICKLE_FILE = 'polygon.pickle'
def main():
with open(PICKLE_FILE, 'rb') as f:
area = pickle.load(f)
with open(GPX_IN_FILE, 'rb') as f:
gpx = gpxpy.parse(f)
gpx.waypoints = list(filter(lambda wp: area.contains(
shapely.Point(wp.latitude, wp.longitude)), gpx.waypoints))
with open(GPX_OUT_FILE, 'w') as f:
f.write(gpx.to_xml())
if __name__ == '__main__':
main()