Make public transport routes discoverable with shareable search

Add one-click examples and route search by number or metadata, with transport type, location and map-area filters. Preserve search filters and bounds in shareable URLs and restore searches on reload and browser navigation.

Validate with 91 passing tests, including desktop and mobile browser coverage, and strict mypy checks.

Closes #2
This commit is contained in:
Edward Betts 2026-09-30 22:23:45 +01:00
parent 29afb4f115
commit a79b0a7098
7 changed files with 919 additions and 12 deletions

View file

@ -7,26 +7,24 @@ from flask.typing import ResponseReturnValue
from osm_geojson.pt.core import (
OsmError,
PUBLIC_TRANSPORT_ROUTE_TYPES,
Bounds,
build_route_coords,
fetch_relation_full,
fetch_relation_name,
fetch_route_master_routes,
fetch_sibling_routes,
find_locations,
make_geojson,
nearest_coord_index,
node_name,
parse_elements,
search_routes,
)
app = Flask(__name__)
app.secret_key = "dev"
PUBLIC_TRANSPORT_ROUTE_TYPES = {
"bus", "trolleybus", "tram", "subway", "train",
"light_rail", "monorail", "ferry", "funicular",
}
def parse_relation_id(text: str) -> int | None:
"""Extract a relation ID from a bare integer, partial path, or full OSM URL."""
text = text.strip()
@ -144,6 +142,36 @@ def api_route(relation_id: int) -> ResponseReturnValue:
})
@app.get("/api/search")
def api_search() -> ResponseReturnValue:
"""Find public transport routes by name, terminus or route number."""
try:
bounds: Bounds | None = None
keys = ("south", "west", "north", "east")
if any(key in request.args for key in keys):
try:
bounds = (
float(request.args["south"]), float(request.args["west"]),
float(request.args["north"]), float(request.args["east"]),
)
except (KeyError, ValueError) as exc:
raise OsmError("All four search area coordinates are required and must be numbers.", 400) from exc
return jsonify(search_routes(request.args.get("q", ""), request.args.get("mode", ""), bounds))
except OsmError as exc:
code = "invalid_query" if exc.status_code == 400 else "osm_error"
return jsonify({"error": code, "message": str(exc)}), exc.status_code
@app.get("/api/locations")
def api_locations() -> ResponseReturnValue:
"""Find candidate locations and their search bounds for a place name."""
try:
return jsonify({"locations": find_locations(request.args.get("q", ""))})
except OsmError as exc:
code = "invalid_query" if exc.status_code == 400 else "osm_error"
return jsonify({"error": code, "message": str(exc)}), exc.status_code
@app.route("/api/segment/<int:relation_id>")
def api_segment(relation_id: int) -> ResponseReturnValue:
"""Return GeoJSON for the segment between two named stops."""

View file

@ -533,12 +533,235 @@ async function loadRouteMaster(relationId) {
// ── Init ───────────────────────────────────────────────────────────────────
let selectedLocation = null;
let searchAreaLayer = null;
const locationInput = document.getElementById('search-location');
const mapAreaCheckbox = document.getElementById('search-map-area');
const locationResults = document.getElementById('location-results');
const areaLabel = document.getElementById('search-area-label');
let searchController = null;
/** Remove the previous search outline when its scope changes. */
function clearSearchArea() {
if (searchAreaLayer) searchAreaLayer.remove();
searchAreaLayer = null;
areaLabel.textContent = '';
}
locationInput.addEventListener('input', () => {
selectedLocation = null;
locationResults.replaceChildren();
clearSearchArea();
});
mapAreaCheckbox.addEventListener('change', () => {
locationInput.disabled = mapAreaCheckbox.checked;
locationResults.replaceChildren();
clearSearchArea();
if (!mapAreaCheckbox.checked && selectedLocation) chooseLocation(selectedLocation);
});
/** Centre the map and show the bounds used for a chosen place. */
function chooseLocation(location) {
selectedLocation = location;
locationResults.replaceChildren();
clearSearchArea();
const [south, west, north, east] = location.bounds;
const bounds = L.latLngBounds([south, west], [north, east]);
searchAreaLayer = L.rectangle(bounds, {
color: '#0d6efd', weight: 2, dashArray: '6 4', fill: false, interactive: false,
}).addTo(map);
map.fitBounds(bounds, { ...fitPadding(), animate: false });
areaLabel.textContent = `Search area: ${location.label}`;
}
/** Search relation metadata, resolving an optional place before searching routes. */
async function searchRoutes({ updateUrl = true, restoredBounds = null } = {}) {
if (searchController) searchController.abort();
const controller = new AbortController();
searchController = controller;
const button = document.getElementById('search-button');
const status = document.getElementById('search-status');
const results = document.getElementById('search-results');
const params = new URLSearchParams({
q: document.getElementById('route-search').value.trim(),
mode: document.getElementById('search-mode').value,
});
button.disabled = true;
locationInput.disabled = true;
mapAreaCheckbox.disabled = true;
results.replaceChildren();
status.textContent = 'Searching routes…';
try {
if (mapAreaCheckbox.checked) {
clearSearchArea();
const bounds = map.getBounds();
// Leaflet wraps world copies; normalise longitude without hiding date-line crossings.
const west = ((bounds.getWest() + 180) % 360 + 360) % 360 - 180;
const east = west + bounds.getEast() - bounds.getWest();
const searchBounds = restoredBounds || [Math.max(-90, bounds.getSouth()), west,
Math.min(90, bounds.getNorth()), east];
['south', 'west', 'north', 'east'].forEach((key, index) => params.set(key, searchBounds[index]));
if (restoredBounds) {
const [south, west, north, east] = restoredBounds;
searchAreaLayer = L.rectangle([[south, west], [north, east]], {
color: '#0d6efd', weight: 2, dashArray: '6 4', fill: false, interactive: false,
}).addTo(map);
}
areaLabel.textContent = restoredBounds ? 'Search area: shared map view' : 'Search area: current map view';
} else if (locationInput.value.trim()) {
if (!selectedLocation) {
status.textContent = 'Finding location…';
const response = await fetch(URLS.locationsApi + '?' + new URLSearchParams({ q: locationInput.value.trim() }), { signal: controller.signal });
const data = await response.json();
if (controller.signal.aborted) return;
if (!response.ok) {
status.textContent = data.message || 'Location search failed. Please try again.';
return;
}
if (!data.locations.length) {
status.textContent = 'No location found. Try a more specific place name.';
return;
}
if (data.locations.length > 1) {
status.textContent = 'Choose a location to search for routes:';
locationResults.replaceChildren();
for (const location of data.locations) {
const choice = document.createElement('button');
choice.type = 'button';
choice.className = 'list-group-item list-group-item-action';
choice.textContent = location.label;
choice.addEventListener('click', () => {
chooseLocation(location);
searchRoutes();
});
locationResults.appendChild(choice);
}
return;
}
chooseLocation(data.locations[0]);
}
['south', 'west', 'north', 'east'].forEach((key, index) => params.set(key, selectedLocation.bounds[index]));
} else {
clearSearchArea();
}
if (updateUrl) {
const urlParams = new URLSearchParams(params);
if (!urlParams.get('mode')) urlParams.delete('mode');
if (mapAreaCheckbox.checked) {
urlParams.set('area', 'map');
} else if (selectedLocation && locationInput.value.trim()) {
urlParams.set('location', locationInput.value.trim());
urlParams.set('place', selectedLocation.label);
}
const url = URLS.indexPage + '?' + urlParams;
if (location.pathname + location.search !== url) history.pushState(null, '', url);
}
status.textContent = 'Searching routes…';
const response = await fetch(URLS.searchApi + '?' + params, { signal: controller.signal });
const data = await response.json();
if (controller.signal.aborted) return;
if (!response.ok) {
status.textContent = data.message || 'Route search failed. Please try again.';
return;
}
status.textContent = data.routes.length
? `${data.routes.length} results. Choose a route to load it.${data.truncated ? ' More matches exist; narrow your search.' : ''}`
: 'No routes found. Try a route number, destination or operator.';
for (const route of data.routes) {
const link = document.createElement('a');
link.href = URLS.routePage + route.id;
link.className = 'list-group-item list-group-item-action';
const name = document.createElement('span');
name.className = 'fw-semibold d-block';
name.textContent = route.name;
const details = document.createElement('span');
details.className = 'text-muted d-block';
details.textContent = [
route.ref, route.route.replaceAll('_', ' '),
route.from && route.to ? `${route.from} → ${route.to}` : route.from || route.to,
route.operator || route.network,
route.type === 'route_master' ? 'All directions' : null,
`Relation ${route.id}`,
].filter(Boolean).join(' · ');
link.append(name, details);
results.appendChild(link);
}
} catch (error) {
if (error.name !== 'AbortError') status.textContent = 'Network error searching routes. Please try again.';
} finally {
if (searchController === controller) {
button.disabled = false;
mapAreaCheckbox.disabled = false;
locationInput.disabled = mapAreaCheckbox.checked;
searchController = null;
}
}
}
/** Restore submitted filters and use the saved bounds exactly, on every screen size. */
function restoreSearch() {
if (searchController) searchController.abort();
searchController = null;
document.getElementById('search-button').disabled = false;
mapAreaCheckbox.disabled = false;
const params = new URLSearchParams(location.search);
document.getElementById('route-search').value = params.get('q') || '';
document.getElementById('search-mode').value = params.get('mode') || '';
locationInput.value = params.get('location') || '';
mapAreaCheckbox.checked = params.get('area') === 'map';
locationInput.disabled = mapAreaCheckbox.checked;
selectedLocation = null;
locationResults.replaceChildren();
clearSearchArea();
document.getElementById('search-results').replaceChildren();
const status = document.getElementById('search-status');
status.textContent = '';
if (!params.has('q')) return;
if (isMobile()) openPanel();
const keys = ['south', 'west', 'north', 'east'];
let bounds = null;
if (keys.some(key => params.has(key))) {
bounds = keys.map(key => params.has(key) && params.get(key).trim() ? Number(params.get(key)) : NaN);
const [south, west, north, east] = bounds;
if (!bounds.every(Number.isFinite) || south < -90 || north > 90 || west < -180 || east > 180
|| south >= north || west >= east || north - south > 20 || east - west > 20) {
status.textContent = 'Invalid search area in this URL. Choose a location or zoom in and search again.';
return;
}
if (mapAreaCheckbox.checked) {
map.fitBounds([[south, west], [north, east]], { ...fitPadding(), animate: false });
} else {
locationInput.value ||= params.get('place') || 'Shared search area';
chooseLocation({ label: params.get('place') || locationInput.value, bounds });
}
} else if (mapAreaCheckbox.checked) {
status.textContent = 'This map search URL is missing its search area. Zoom in and search again.';
return;
}
const query = document.getElementById('route-search').value.trim();
const mode = params.get('mode') || '';
if (query.length < 2 || query.length > 100 || /[\x00-\x1f]/.test(query)
|| (mode && document.getElementById('search-mode').value !== mode)) {
status.textContent = 'Invalid search filters in this URL. Update the filters and search again.';
return;
}
searchRoutes({ updateUrl: false, restoredBounds: bounds });
}
document.getElementById('route-search-form').addEventListener('submit', (event) => {
event.preventDefault();
locationResults.replaceChildren();
searchRoutes();
});
window.addEventListener('popstate', () => {
const prefix = URLS.routePage;
if (location.pathname.startsWith(prefix)) {
const id = parseInt(location.pathname.slice(prefix.length), 10);
if (id) loadRoute(id);
}
restoreSearch();
});
if (RELATION_ID) {
@ -546,3 +769,4 @@ if (RELATION_ID) {
} else if (isMobile()) {
openPanel();
}
restoreSearch();

View file

@ -28,9 +28,35 @@
<p>All endpoints are read-only and require no authentication. Data is fetched
live from the <a href="https://wiki.openstreetmap.org/wiki/API_v0.6">OSM API v0.6</a>.
Relation IDs can be found on
<a href="https://www.openstreetmap.org">openstreetmap.org</a> — search for a
route and click through to its relation page.</p>
Route search uses <a href="https://wiki.openstreetmap.org/wiki/Overpass_API">Overpass</a>
to find relation IDs by route metadata.</p>
<h2><span class="badge bg-primary me-2">GET</span><code>/api/search?q=TEXT&amp;mode=TYPE</code></h2>
<p>Search worldwide for public transport <code>route</code> and <code>route_master</code>
relations. Required <code>q</code> is 2–100 characters. Route numbers (<code>ref</code>)
match exactly; names, termini, operators and networks match literal substrings,
case-insensitively. Optional <code>mode</code> filters by a supported transport type.</p>
<p>Optional <code>south</code>, <code>west</code>, <code>north</code> and <code>east</code>
coordinates restrict the search to routes with mapped members within a bounding box,
including their parent route masters. All four coordinates are required together.
Routes may extend outside the box. Bounds must be finite and ordered, span at most
20 degrees in either direction, and must not cross the date line.</p>
<p>Returns <code>{"routes": [...], "truncated": false}</code>. Each result has
<code>id</code>, <code>name</code>, <code>ref</code>, <code>from</code>, <code>to</code>,
<code>operator</code>, <code>network</code>, <code>route</code> (transport type) and
<code>type</code> (relation type). At most 50 results are returned; <code>truncated</code>
indicates more matches. No matches returns an empty list. Invalid input returns
400 <code>invalid_query</code>; upstream failures return 502 <code>osm_error</code>.</p>
<pre>GET /api/search?q=M11&amp;mode=subway</pre>
<pre>GET /api/search?q=24&amp;mode=bus&amp;south=51.39&amp;west=-2.73&amp;north=51.55&amp;east=-2.51</pre>
<h2><span class="badge bg-primary me-2">GET</span><code>/api/locations?q=PLACE</code></h2>
<p>Find up to five candidate places using Nominatim. Required <code>q</code> is 2–100
characters. Returns <code>{"locations": [{"label": "...", "bounds": [south, west, north, east]}]}</code>.
An empty list means no matching location. Invalid input returns 400 <code>invalid_query</code>;
upstream failures return 502 <code>osm_error</code>. Location lookups are submitted explicitly,
cached and limited to one upstream request per second per application process.</p>
<pre>GET /api/locations?q=Bristol%2C+UK</pre>
<p>All error responses return JSON with at least <code>error</code> (machine-readable
code) and <code>message</code> (human-readable description) fields.</p>

View file

@ -32,15 +32,90 @@
<!-- Scrollable content area -->
<div id="sidebar-inner">
<form id="route-search-form" class="mb-3">
<label for="route-search" class="form-label fw-semibold small">Find a public transport route</label>
<div class="input-group input-group-sm mb-2">
<input id="route-search" type="search" class="form-control" required
minlength="2" maxlength="100" placeholder="e.g. M11 or Bristol Airport"
aria-describedby="search-help">
<button id="search-button" class="btn btn-primary" type="submit">Search</button>
</div>
<label for="search-mode" class="visually-hidden">Transport type</label>
<select id="search-mode" class="form-select form-select-sm">
<option value="">All transport types</option>
<option value="bus">Bus</option>
<option value="trolleybus">Trolleybus</option>
<option value="tram">Tram</option>
<option value="subway">Subway / metro</option>
<option value="train">Train</option>
<option value="light_rail">Light rail</option>
<option value="monorail">Monorail</option>
<option value="ferry">Ferry</option>
<option value="funicular">Funicular</option>
</select>
<label for="search-location" class="form-label small mt-2 mb-1">Location (optional)</label>
<input id="search-location" class="form-control form-control-sm" type="text"
minlength="2" maxlength="100" placeholder="e.g. Bristol, UK" autocomplete="off"
aria-describedby="search-area-help">
<div class="form-check mt-2">
<input id="search-map-area" class="form-check-input" type="checkbox">
<label for="search-map-area" class="form-check-label small">Search this map area</label>
</div>
<p id="search-help" class="form-text mb-0">Search by route number, name,
destination, operator or network. Route numbers match exactly.</p>
<p id="search-area-help" class="form-text mb-0">Leave location blank to search worldwide,
or limit to a place or the current map view. Routes can extend outside the area.</p>
<p id="search-area-label" class="small mt-2 mb-0"></p>
<p class="form-text mb-0">After searching, copy the page URL to share these filters.</p>
<div id="location-results" class="list-group small mt-2"></div>
<p id="search-status" class="small mt-2 mb-0" role="status" aria-live="polite"></p>
<div id="search-results" class="list-group small mt-2"></div>
</form>
<!-- A first route is one click away; no OSM knowledge required. -->
<details class="mb-3"{% if not relation_id %} open{% endif %}>
<summary class="fw-semibold">Try a public transport route</summary>
<p class="small mt-2 mb-2">View a route on the map and download it as GeoJSON.
Choose an example to get started:</p>
<div class="list-group small mb-2">
<a class="list-group-item list-group-item-action"
href="{{ url_for('route_page', relation_id=18892969) }}">
<span class="fw-semibold d-block">Bristol airport bus A1</span>
<span class="text-muted">Airport → Bus Station · Bus</span>
</a>
<a class="list-group-item list-group-item-action"
href="{{ url_for('route_page', relation_id=15083963) }}">
<span class="fw-semibold d-block">Istanbul Metro M11</span>
<span class="text-muted">One direction · Subway</span>
</a>
<a class="list-group-item list-group-item-action"
href="{{ url_for('route_page', relation_id=15083966) }}">
<span class="fw-semibold d-block">Istanbul M11 — all directions</span>
<span class="text-muted">Compare routes, then choose a direction</span>
</a>
</div>
<details{% if not relation_id %} open{% endif %} class="small">
<summary class="fw-semibold">How to use this tool</summary>
<ol class="ps-3 mt-2 mb-0">
<li>Search and choose a result, try an example, or paste a route URL below.</li>
<li>Download the full route, or select a start stop and then an end stop to preview a segment.</li>
<li>Choose whether to include stops, then download your GeoJSON file.</li>
</ol>
</details>
</details>
<!-- Load form -->
<form method="post" action="{{ url_for('load') }}" class="mb-3">
<label class="form-label fw-semibold small">Relation ID or OSM URL</label>
<label for="relation-input" class="form-label fw-semibold small">Load your own route</label>
<div class="input-group input-group-sm">
<input type="text" name="relation" class="form-control"
placeholder="e.g. 15083963"
<input type="text" name="relation" id="relation-input" class="form-control"
placeholder="Relation ID or OSM URL" aria-describedby="relation-help" required
value="{{ relation_id or '' }}">
<button class="btn btn-primary" type="submit">Load</button>
</div>
<p id="relation-help" class="form-text mb-0">Paste an OpenStreetMap route relation URL
(e.g. https://www.openstreetmap.org/relation/15083963) or its numeric ID.
A relation groups the ways and stops belonging to a route.</p>
</form>
<!-- Error alert -->
@ -141,6 +216,9 @@
// Injected by Flask so app.js works correctly under any mount path.
const RELATION_ID = {{ relation_id | tojson }};
const URLS = {
indexPage: {{ url_for('index') | tojson }},
searchApi: {{ url_for('api_search') | tojson }},
locationsApi: {{ url_for('api_locations') | tojson }},
routeApi: {{ url_for('api_route', relation_id=0)[:-1] | tojson }},
segmentApi: {{ url_for('api_segment', relation_id=0)[:-1] | tojson }},
routeMasterApi: {{ url_for('api_route_master', relation_id=0)[:-1] | tojson }},