index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import bearing from "@turf/bearing";
  2. import destination from "@turf/destination";
  3. import measureDistance from "@turf/distance";
  4. import { point } from "@turf/helpers";
  5. import { getGeom } from "@turf/invariant";
  6. /**
  7. * Takes a {@link LineString} and returns a {@link Point} at a specified distance along the line.
  8. *
  9. * @name along
  10. * @param {Feature<LineString>} line input line
  11. * @param {number} distance distance along the line
  12. * @param {Object} [options] Optional parameters
  13. * @param {string} [options.units="kilometers"] can be degrees, radians, miles, or kilometers
  14. * @returns {Feature<Point>} Point `distance` `units` along the line
  15. * @example
  16. * var line = turf.lineString([[-83, 30], [-84, 36], [-78, 41]]);
  17. * var options = {units: 'miles'};
  18. *
  19. * var along = turf.along(line, 200, options);
  20. *
  21. * //addToMap
  22. * var addToMap = [along, line]
  23. */
  24. export default function along(line, distance, options) {
  25. if (options === void 0) { options = {}; }
  26. // Get Coords
  27. var geom = getGeom(line);
  28. var coords = geom.coordinates;
  29. var travelled = 0;
  30. for (var i = 0; i < coords.length; i++) {
  31. if (distance >= travelled && i === coords.length - 1) {
  32. break;
  33. }
  34. else if (travelled >= distance) {
  35. var overshot = distance - travelled;
  36. if (!overshot) {
  37. return point(coords[i]);
  38. }
  39. else {
  40. var direction = bearing(coords[i], coords[i - 1]) - 180;
  41. var interpolated = destination(coords[i], overshot, direction, options);
  42. return interpolated;
  43. }
  44. }
  45. else {
  46. travelled += measureDistance(coords[i], coords[i + 1], options);
  47. }
  48. }
  49. return point(coords[coords.length - 1]);
  50. }