59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
import * as turfHelpers from "@turf/helpers";
|
|
import dijkstra from "dijkstrajs";
|
|
import network from "./network.json";
|
|
|
|
// Transform the navigation graph to be in the format expected by dijkstrajs
|
|
const graph = {};
|
|
|
|
for (const [beginId, begin] of Object.entries(network.navigation)) {
|
|
const neighbors = {};
|
|
|
|
for (const [endId, end] of Object.entries(begin)) {
|
|
neighbors[endId] = end.properties.length;
|
|
}
|
|
|
|
graph[beginId] = neighbors;
|
|
}
|
|
|
|
/**
|
|
* Find the shortest path of nodes linking two nodes or stops.
|
|
* @param {string} from ID of the starting stop or node.
|
|
* @param {string} to ID of the ending stop or node.
|
|
* @return {Array.<string>} If possible, list of nodes joining `from` to `to`.
|
|
*/
|
|
export const findPath = (from, to) => {
|
|
try {
|
|
return dijkstra.find_path(graph, from, to);
|
|
} catch (err) {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Find the shortest segment linking two nodes or stops.
|
|
* @param {string} from ID of the starting stop or node.
|
|
* @param {string} to ID of the ending stop or node.
|
|
* @return {LineString?} If it exists, a segment linking the two nodes.
|
|
*/
|
|
export const findSegment = (from, to) => {
|
|
const path = findPath(from, to);
|
|
|
|
if (path === null) {
|
|
return null;
|
|
}
|
|
|
|
const initial = network.navigation[path[0]][path[1]];
|
|
let points = [...initial.geometry.coordinates];
|
|
let length = initial.properties.length;
|
|
|
|
for (let i = 1; i + 1 < path.length; ++i) {
|
|
const current = network.navigation[path[i]][path[i + 1]];
|
|
points = points.concat(current.geometry.coordinates.slice(1));
|
|
length += current.properties.length;
|
|
}
|
|
|
|
const route = turfHelpers.lineString(points);
|
|
route.properties.length = length;
|
|
return route;
|
|
};
|