index.js 2.2 KB

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