Open
Description
Hiya, I am using this geojson data source which supplied canals in the UK.
I was hoping to be able to use this library to be able to highlight a section of one of the rivers to show for example a "cruise" between two locations. However when trying to run the function I receive undefined
from the return value of findPath().
Am i doing something wrong, or is there a way to achieve this? Thanks so much for any and all advice!
Code:
import {
Feature,
FeatureCollection,
LineString,
Point,
nearestPointOnLine,
point,
} from "@turf/turf";
// Here is the pathFinder import
import PathFinder, { pathToGeoJSON } from "geojson-path-finder";
// Custom LatLngAlt type
type LatLngAlt = {
lat: number;
lng: number;
alt?: number;
};
// This is just to get the coords for the below function
const toCoordinate = (latlng: LatLngAlt): [number, number] => {
return [latlng.lng, latlng.lat];
};
/* I found this function in another issue, it just ensures that the points get snapped to the nearest line just in case the GPS coords are slightly off */
const insertProjectedPointToClosestLine = (
latlng: LatLngAlt,
collection: FeatureCollection<LineString>
) => {
let closestLine = null;
let nearestPoint = null;
let minimalDistance = Infinity;
let coordinates = toCoordinate(latlng);
for (let feature of collection.features) {
let point = nearestPointOnLine(feature, coordinates);
if (point.properties.dist < minimalDistance) {
minimalDistance = point.properties.dist;
closestLine = feature;
nearestPoint = point;
}
}
closestLine.geometry.coordinates.splice(
nearestPoint.properties.index + 1,
0,
nearestPoint.geometry.coordinates
);
return nearestPoint.geometry.coordinates as [number, number];
};
// This is the function that is returning undefined from findPath()
export function getShortestPath(
lineData: FeatureCollection<LineString>,
start: Feature<Point>,
end: Feature<Point>
) {
const pathFinder = new PathFinder(lineData);
const startPointCoords = insertProjectedPointToClosestLine(
{ lat: start.geometry.coordinates[1], lng: start.geometry.coordinates[0] },
lineData
);
const endPointCoords = insertProjectedPointToClosestLine(
{ lat: end.geometry.coordinates[1], lng: end.geometry.coordinates[0] },
lineData
);
const startPointFeature = point(startPointCoords);
const endPointFeature = point(endPointCoords);
const pathResult = pathFinder.findPath(startPointFeature, endPointFeature);
if (!pathResult) {
console.error("Path not found");
}
return pathToGeoJSON(pathResult);
}
Metadata
Metadata
Assignees
Labels
No labels