UNPKG

@turf/line-slice-along

Version:

Useful for extracting only the part of a route between two distances.

58 lines 2.15 kB
// index.ts import { bearing } from "@turf/bearing"; import { distance } from "@turf/distance"; import { destination } from "@turf/destination"; import { lineString, isObject } from "@turf/helpers"; function lineSliceAlong(line, startDist, stopDist, options = {}) { if (!isObject(options)) throw new Error("options is invalid"); const { units = "kilometers" } = options; var coords; var slice = []; if (line.type === "Feature") coords = line.geometry.coordinates; else if (line.type === "LineString") coords = line.coordinates; else throw new Error("input must be a LineString Feature or Geometry"); const origCoordsLength = coords.length; let travelled = 0; let overshot, direction, interpolated; for (let i = 0; i < coords.length; i++) { if (startDist >= travelled && i === coords.length - 1) break; else if (travelled > startDist && slice.length === 0) { let overshot2 = startDist - travelled; if (!overshot2) { slice.push(coords[i]); return lineString(slice); } direction = bearing(coords[i], coords[i - 1]) - 180; interpolated = destination(coords[i], overshot2, direction, { units }); slice.push(interpolated.geometry.coordinates); } if (travelled >= stopDist) { overshot = stopDist - travelled; if (!overshot) { slice.push(coords[i]); return lineString(slice); } direction = bearing(coords[i], coords[i - 1]) - 180; interpolated = destination(coords[i], overshot, direction, { units }); slice.push(interpolated.geometry.coordinates); return lineString(slice); } if (travelled >= startDist) { slice.push(coords[i]); } if (i === coords.length - 1) { return lineString(slice); } travelled += distance(coords[i], coords[i + 1], { units }); } if (travelled < startDist && coords.length === origCoordsLength) throw new Error("Start position is beyond line"); var last = coords[coords.length - 1]; return lineString([last, last]); } var index_default = lineSliceAlong; export { index_default as default, lineSliceAlong }; //# sourceMappingURL=index.js.map