From ba60e4b6836f93cb23a5a777cf4753bbbc547bf7 Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Fri, 12 Jan 2024 22:29:10 +0000 Subject: [PATCH] Show rail routes using GeoJSON --- templates/trip_page.html | 16 +++++++++++++--- web_view.py | 39 ++++++++++++++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/templates/trip_page.html b/templates/trip_page.html index f7c6e14..b49bb6f 100644 --- a/templates/trip_page.html +++ b/templates/trip_page.html @@ -124,10 +124,20 @@ coordinates.forEach(function(item) { marker.bindPopup(item.name); }); -// Draw lines for routes +// Draw routes routes.forEach(function(route) { - var color = route[0] === "train" ? "green" : "red"; // Green for trains, red for flights - L.polyline([route[1], route[2]], {color: color}).addTo(map); + if (route.geojson) { + // If route is defined as GeoJSON + L.geoJSON(JSON.parse(route.geojson), { + style: function(feature) { + return {color: route.type === "train" ? "green" : "blue"}; // Green for trains, blue for flights + } + }).addTo(map); + } else { + // If route is defined by 'from' and 'to' coordinates + var color = route.type === "train" ? "green" : "red"; // Green for trains, red for flights + L.polyline([route.from, route.to], {color: color}).addTo(map); + } }); diff --git a/web_view.py b/web_view.py index 18077c4..ccb8c87 100755 --- a/web_view.py +++ b/web_view.py @@ -301,23 +301,52 @@ def latlon_tuple(stop: StrDict) -> tuple[float, float]: return (stop["latitude"], stop["longitude"]) -def get_trip_routes( - trip: Trip, -) -> list[tuple[str, tuple[float, float], tuple[float, float]]]: +def read_geojson(filename: str) -> str: + data_dir = app.config["PERSONAL_DATA"] + return open(os.path.join(data_dir, "train_routes", filename + ".geojson")).read() + + +def get_trip_routes(trip: Trip) -> list[StrDict]: routes = [] + seen_geojson = set() for t in trip.travel: if t["type"] == "flight": if "from_airport" not in t or "to_airport" not in t: continue fly_from, fly_to = t["from_airport"], t["to_airport"] - routes.append(("flight", latlon_tuple(fly_from), latlon_tuple(fly_to))) + routes.append( + { + "type": "flight", + "from": latlon_tuple(fly_from), + "to": latlon_tuple(fly_to), + } + ) else: assert t["type"] == "train" for leg in t["legs"]: train_from, train_to = leg["from_station"], leg["to_station"] + geojson_filename = train_from.get("routes", {}).get(train_to["uic"]) + print(train_from["name"], train_to["name"], geojson_filename) + if not geojson_filename: + routes.append( + { + "type": "train", + "from": latlon_tuple(train_from), + "to": latlon_tuple(train_to), + } + ) + continue + + if geojson_filename in seen_geojson: + continue + seen_geojson.add(geojson_filename) + routes.append( - ("train", latlon_tuple(train_from), latlon_tuple(train_to)) + { + "type": "train", + "geojson": read_geojson(geojson_filename), + } ) return routes