Skip to content

Instantly share code, notes, and snippets.

@gislars
Created September 5, 2023 13:53
Show Gist options
  • Save gislars/fed2816e9e0c387c35d77ab1edd4e770 to your computer and use it in GitHub Desktop.
Save gislars/fed2816e9e0c387c35d77ab1edd4e770 to your computer and use it in GitHub Desktop.
get route from OSRM and within a buffer of that route all charging stations
from routingpy.routers import OSRM
import overpy
import json
from shapely.geometry import LineString, mapping
def query_overpass(route_file):
with open(route_file, 'r') as f:
route_data = json.load(f)
# Geometrie extrahieren
route_geometry = route_data['routes'][0]['geometry']
# Speichere die Route in 'route_export.geojson', nuetzlich fuer debug z.B. mit geojson.io
with open('route_export.geojson', 'w') as outfile:
json.dump(route_geometry, outfile)
line = LineString(route_geometry['coordinates'])
# puffern mit 1000m, sehr grob umgerechnet in 0.01 Grad
buffer_distance = 0.01
buffer = line.buffer(buffer_distance)
# Speichere den Puffer als GeoJSON-Datei, nuetzlich fuer debug
with open('route_buffer.geojson', 'w') as buffer_file:
json.dump(mapping(buffer), buffer_file)
# Koordinaten der Flaeche bestimmen, benoetigt fuer overpass-Abfrage
poly_coords = ' '.join(f"{coord[1]} {coord[0]}" for coord in buffer.exterior.coords)
# Overpass-Abfrage mit Beschraenkung auf Flaeche
api = overpy.Overpass()
query = f"""
[out:json];
(
node["amenity"="charging_station"](poly:"{poly_coords}");
);
out geom;
"""
results = api.query(query)
charging_stations = []
for node in results.nodes:
if "amenity" in node.tags and node.tags["amenity"] == "charging_station":
charging_stations.append(node)
# Konvertiere die Ergebnisse in GeoJSON
def nodes_to_geojson(nodes):
return {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [float(node.lon), float(node.lat)]
},
"properties": node.tags
} for node in nodes]
}
with open('charging_stations.geojson', 'w') as outfile:
json.dump(nodes_to_geojson(charging_stations), outfile)
def calculate_route(start_coords, end_coords, filename):
# andere moeglich, siehe https://routingpy.readthedocs.io/en/latest/?badge=latest#module-routingpy.routers
router = OSRM()
# Route zwischen Start und Ziel berechnen
route = router.directions(locations=[start_coords, end_coords], profile='driving', dry_run=False, geometries='geojson')
with open(filename, 'w') as outfile:
json.dump(route.raw, outfile)
start_coords = (13.00392, 52.71465) # Berlin
end_coords = (9.48127, 53.89224) # Hamburg
calculate_route(start_coords, end_coords, 'route.geojson')
query_overpass('route.geojson')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment