Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | 27x 107x 5x 30x 5x 15x 30x 30x 30x 15x 15x 30x 10x 10x 36x 36x 11x 11x 10x 5x 5x 5x 5x 5x 5x 5x 14x 14x 14x 4x 12x 4x 10x 10x 10x 14x 14x 9x 9x 9x 10x 10x 10x 10x 29x 57x 57x 25x 10x 10x 10x 10x 10x 10x 10x 9x 9x 1x 1x 32x 32x 32x 32x 32x 32x 66x 66x 33x 30x 30x 57x 27x 27x 27x 27x 27x 24x 57x 57x 5x 5x 4x 19x 19x 19x 19x 19x 19x 19x 19x 19x 3x 3x 57x 10x 10x | import { Feature, FeatureCollection, LineString, MultiLineString, Position } from "geojson";
import distance from "@turf/distance";
import type { RouteDataResultSet, TripPlannerItinerary, TripPlannerLeg } from "@overworld/trimet-client";
import type { WalkingRoute } from "./walking";
import { getSelectedRouteSegment } from "./routeSegment";
export type PlannerPath = LineString | MultiLineString;
export type PlannerPathProperties = { trip: number; legIndex: number; walk: boolean; color?: string };
type Path = PlannerPath;
type TripProperties = PlannerPathProperties;
export interface PlannerPathProviders {
getRouteById(routeId: number, signal: AbortSignal): Promise<RouteDataResultSet>;
getRouteGeometry(routeId: string, direction: number, signal: AbortSignal): Promise<Feature<Path>>;
getWalkingPath(origin: number[], destination: number[], signal: AbortSignal): Promise<WalkingRoute>;
routeId(leg: TripPlannerLeg): number;
transitColor(leg: TripPlannerLeg): string;
}
const MAX_SNAP_MILES = 0.075;
function getDistance(from: Position, to: Position) {
return distance(from, to, { units: "miles" });
}
function connectedShape(lines: Position[][], origin: Position, destination: Position) {
// The bundled shapes may contain repeated and unordered segments from many trips.
const graph = new Map<string, { point: Position; neighbors: Set<string> }>();
const keyOf = ([lng, lat]: Position) => `${lng.toFixed(7)},${lat.toFixed(7)}`;
for (const line of lines) {
let previous: string | undefined;
for (const point of line) {
const key = keyOf(point);
if (!graph.has(key)) graph.set(key, { point, neighbors: new Set() });
if (previous && previous !== key) {
graph.get(previous).neighbors.add(key);
graph.get(key).neighbors.add(previous);
}
previous = key;
}
}
function snap(point: Position) {
let nearest: string | undefined;
let distance = MAX_SNAP_MILES;
graph.forEach((node, key) => {
const candidate = getDistance(point, node.point);
if (candidate < distance) {
nearest = key;
distance = candidate;
}
});
return nearest;
}
const start = snap(origin);
const end = snap(destination);
Iif (!start || !end || start === end) return;
const open = new Set([start]);
const distances = new Map([[start, 0]]);
const previous = new Map<string, string>();
while (open.size) {
let current: string | undefined;
open.forEach(key => {
Eif (!current || distances.get(key) < distances.get(current)) current = key;
});
if (current === end) {
const path: Position[] = [];
for (let key = end; key; key = previous.get(key)) path.push(graph.get(key).point);
return path.reverse();
}
open.delete(current);
const node = graph.get(current);
node.neighbors.forEach(neighbor => {
const distance = distances.get(current) + getDistance(node.point, graph.get(neighbor).point);
if (distance < (distances.get(neighbor) ?? Infinity)) {
distances.set(neighbor, distance);
previous.set(neighbor, current);
open.add(neighbor);
}
});
}
}
export async function loadPlannerPaths(
itineraries: TripPlannerItinerary[],
signal: AbortSignal,
walkingEnabled: boolean,
{ getRouteById, getRouteGeometry, getWalkingPath, routeId, transitColor }: PlannerPathProviders
) {
const routes = new Map<number, ReturnType<typeof getRouteById>>();
const shapes = new Map<string, ReturnType<typeof getRouteGeometry>>();
const walks = new Map<string, ReturnType<typeof getWalkingPath>>();
const coverage = await Promise.all(itineraries.map(async (itinerary, trip) => {
const legs = await Promise.all(itinerary.legs.map(async (leg, legIndex): Promise<Feature<Path, TripProperties> | undefined> => {
const { from, to } = leg;
if (leg.mode?.toLowerCase() === "walk") {
if (!walkingEnabled || ![from?.lon, from?.lat, to?.lon, to?.lat].every(Number.isFinite)) return;
const origin = [from.lon, from.lat];
const destination = [to.lon, to.lat];
Iif (origin[0] === destination[0] && origin[1] === destination[1]) return;
const key = JSON.stringify([origin, destination]);
try {
if (!walks.has(key)) walks.set(key, getWalkingPath(origin, destination, signal));
const path = await walks.get(key);
Eif (path.status === "ready") {
return { ...path.feature, properties: { trip, legIndex, walk: true } };
}
} catch (error) {
Eif (!signal.aborted) console.warn(`Could not load walking geometry for trip ${trip}, leg ${legIndex}`, error);
}
return;
}
const id = routeId(leg);
Iif (!Number.isInteger(id) || id <= 0 || !from?.stopId || !to?.stopId ||
from.stopId === to.stopId) return;
if (!routes.has(id)) routes.set(id, getRouteById(id, signal));
try {
const config = await routes.get(id);
const matches = (config.route ?? []).flatMap(routeConfig =>
(routeConfig.dir ?? []).flatMap(direction => {
const origins = (direction.stop ?? []).filter(stop => stop.locid === from.stopId);
const destinations = (direction.stop ?? []).filter(stop => stop.locid === to.stopId);
return origins.flatMap(origin => destinations
.filter(destination => origin.seq < destination.seq)
.map(destination => ({ direction: direction.dir, origin, destination })));
})
);
if (matches.length !== 1 || signal.aborted) return;
const { direction, origin, destination } = matches[0];
const properties = { trip, legIndex, walk: false, color: transitColor(leg) };
const key = `${id}/${direction}`;
if (!shapes.has(key)) shapes.set(key, getRouteGeometry(String(id), direction, signal));
const shape = await shapes.get(key);
const originPoint = [from.lon ?? origin.lng, from.lat ?? origin.lat];
const destinationPoint = [to.lon ?? destination.lng, to.lat ?? destination.lat];
if (shape.geometry.type === "MultiLineString") {
const coordinates = connectedShape(shape.geometry.coordinates, originPoint, destinationPoint);
if (!coordinates) return;
return { type: "Feature", geometry: { type: "LineString", coordinates }, properties };
}
const { geometry } = getSelectedRouteSegment(shape, origin, destination);
Iif (geometry.type !== "LineString") return;
const { coordinates } = geometry;
const start = coordinates[0];
const end = coordinates[coordinates.length - 1];
const matchesEndpoints = (a: Position, b: Position) =>
getDistance(a, originPoint) <= MAX_SNAP_MILES &&
getDistance(b, destinationPoint) <= MAX_SNAP_MILES;
Iif ((!matchesEndpoints(start, end) && !matchesEndpoints(end, start)) ||
getDistance(start, end) === 0) return;
return { type: "Feature", geometry, properties };
} catch (error) {
Eif (!signal.aborted) console.warn(`Could not load transit geometry for trip ${trip}, leg ${legIndex}`, error);
return undefined;
}
}));
return legs.filter((path): path is Feature<Path, TripProperties> => Boolean(path));
}));
const data: FeatureCollection<Path, TripProperties> = {
type: "FeatureCollection",
features: coverage.flat()
};
return { data };
}
|