@turf/line-slice
Version:
Useful for extracting only the part of a route between waypoints.
32 lines • 1.4 kB
JavaScript
// index.ts
import { getCoords, getType } from "@turf/invariant";
import { lineString as linestring } from "@turf/helpers";
import { nearestPointOnLine } from "@turf/nearest-point-on-line";
function lineSlice(startPt, stopPt, line) {
const coords = getCoords(line);
if (getType(line) !== "LineString")
throw new Error("line must be a LineString");
const startVertex = nearestPointOnLine(line, startPt);
const stopVertex = nearestPointOnLine(line, stopPt);
fixSegmentIndexBounds(line, startVertex);
fixSegmentIndexBounds(line, stopVertex);
const ends = startVertex.properties.segmentIndex <= stopVertex.properties.segmentIndex ? [startVertex, stopVertex] : [stopVertex, startVertex];
const clipCoords = [ends[0].geometry.coordinates];
for (let i = ends[0].properties.segmentIndex + 1; i < ends[1].properties.segmentIndex + 1; i++) {
clipCoords.push(coords[i]);
}
clipCoords.push(ends[1].geometry.coordinates);
return linestring(clipCoords, line.type === "Feature" ? line.properties : {});
}
function fixSegmentIndexBounds(line, vertex) {
let geometry = line.type === "Feature" ? line.geometry : line;
if (vertex.properties.segmentIndex >= geometry.coordinates.length - 1) {
vertex.properties.segmentIndex = geometry.coordinates.length - 2;
}
}
var index_default = lineSlice;
export {
index_default as default,
lineSlice
};
//# sourceMappingURL=index.js.map