index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { getCoords, getType } from '@turf/invariant';
  2. import { lineString } from '@turf/helpers';
  3. import nearestPointOnLine from '@turf/nearest-point-on-line';
  4. /**
  5. * Takes a {@link LineString|line}, a start {@link Point}, and a stop point
  6. * and returns a subsection of the line in-between those points.
  7. * The start & stop points don't need to fall exactly on the line.
  8. *
  9. * This can be useful for extracting only the part of a route between waypoints.
  10. *
  11. * @name lineSlice
  12. * @param {Coord} startPt starting point
  13. * @param {Coord} stopPt stopping point
  14. * @param {Feature<LineString>|LineString} line line to slice
  15. * @returns {Feature<LineString>} sliced line
  16. * @example
  17. * var line = turf.lineString([
  18. * [-77.031669, 38.878605],
  19. * [-77.029609, 38.881946],
  20. * [-77.020339, 38.884084],
  21. * [-77.025661, 38.885821],
  22. * [-77.021884, 38.889563],
  23. * [-77.019824, 38.892368]
  24. * ]);
  25. * var start = turf.point([-77.029609, 38.881946]);
  26. * var stop = turf.point([-77.021884, 38.889563]);
  27. *
  28. * var sliced = turf.lineSlice(start, stop, line);
  29. *
  30. * //addToMap
  31. * var addToMap = [start, stop, line]
  32. */
  33. function lineSlice(startPt, stopPt, line) {
  34. // Validation
  35. var coords = getCoords(line);
  36. if (getType(line) !== "LineString")
  37. throw new Error("line must be a LineString");
  38. var startVertex = nearestPointOnLine(line, startPt);
  39. var stopVertex = nearestPointOnLine(line, stopPt);
  40. var ends;
  41. if (startVertex.properties.index <= stopVertex.properties.index) {
  42. ends = [startVertex, stopVertex];
  43. } else {
  44. ends = [stopVertex, startVertex];
  45. }
  46. var clipCoords = [ends[0].geometry.coordinates];
  47. for (
  48. var i = ends[0].properties.index + 1;
  49. i < ends[1].properties.index + 1;
  50. i++
  51. ) {
  52. clipCoords.push(coords[i]);
  53. }
  54. clipCoords.push(ends[1].geometry.coordinates);
  55. return lineString(clipCoords, line.properties);
  56. }
  57. export default lineSlice;