index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // http://en.wikipedia.org/wiki/Haversine_formula
  2. // http://www.movable-type.co.uk/scripts/latlong.html
  3. import { degreesToRadians, lengthToRadians, point, radiansToDegrees, } from "@turf/helpers";
  4. import { getCoord } from "@turf/invariant";
  5. /**
  6. * Takes a {@link Point} and calculates the location of a destination point given a distance in
  7. * degrees, radians, miles, or kilometers; and bearing in degrees.
  8. * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
  9. *
  10. * @name destination
  11. * @param {Coord} origin starting point
  12. * @param {number} distance distance from the origin point
  13. * @param {number} bearing ranging from -180 to 180
  14. * @param {Object} [options={}] Optional parameters
  15. * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
  16. * @param {Object} [options.properties={}] Translate properties to Point
  17. * @returns {Feature<Point>} destination point
  18. * @example
  19. * var point = turf.point([-75.343, 39.984]);
  20. * var distance = 50;
  21. * var bearing = 90;
  22. * var options = {units: 'miles'};
  23. *
  24. * var destination = turf.destination(point, distance, bearing, options);
  25. *
  26. * //addToMap
  27. * var addToMap = [point, destination]
  28. * destination.properties['marker-color'] = '#f00';
  29. * point.properties['marker-color'] = '#0f0';
  30. */
  31. export default function destination(origin, distance, bearing, options) {
  32. if (options === void 0) { options = {}; }
  33. // Handle input
  34. var coordinates1 = getCoord(origin);
  35. var longitude1 = degreesToRadians(coordinates1[0]);
  36. var latitude1 = degreesToRadians(coordinates1[1]);
  37. var bearingRad = degreesToRadians(bearing);
  38. var radians = lengthToRadians(distance, options.units);
  39. // Main
  40. var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +
  41. Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));
  42. var longitude2 = longitude1 +
  43. Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));
  44. var lng = radiansToDegrees(longitude2);
  45. var lat = radiansToDegrees(latitude2);
  46. return point([lng, lat], options.properties);
  47. }