index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { degreesToRadians, radiansToDegrees } from "@turf/helpers";
  2. import { getCoord } from "@turf/invariant";
  3. // http://en.wikipedia.org/wiki/Haversine_formula
  4. // http://www.movable-type.co.uk/scripts/latlong.html
  5. /**
  6. * Takes two {@link Point|points} and finds the geographic bearing between them,
  7. * i.e. the angle measured in degrees from the north line (0 degrees)
  8. *
  9. * @name bearing
  10. * @param {Coord} start starting Point
  11. * @param {Coord} end ending Point
  12. * @param {Object} [options={}] Optional parameters
  13. * @param {boolean} [options.final=false] calculates the final bearing if true
  14. * @returns {number} bearing in decimal degrees, between -180 and 180 degrees (positive clockwise)
  15. * @example
  16. * var point1 = turf.point([-75.343, 39.984]);
  17. * var point2 = turf.point([-75.534, 39.123]);
  18. *
  19. * var bearing = turf.bearing(point1, point2);
  20. *
  21. * //addToMap
  22. * var addToMap = [point1, point2]
  23. * point1.properties['marker-color'] = '#f00'
  24. * point2.properties['marker-color'] = '#0f0'
  25. * point1.properties.bearing = bearing
  26. */
  27. export default function bearing(start, end, options) {
  28. if (options === void 0) { options = {}; }
  29. // Reverse calculation
  30. if (options.final === true) {
  31. return calculateFinalBearing(start, end);
  32. }
  33. var coordinates1 = getCoord(start);
  34. var coordinates2 = getCoord(end);
  35. var lon1 = degreesToRadians(coordinates1[0]);
  36. var lon2 = degreesToRadians(coordinates2[0]);
  37. var lat1 = degreesToRadians(coordinates1[1]);
  38. var lat2 = degreesToRadians(coordinates2[1]);
  39. var a = Math.sin(lon2 - lon1) * Math.cos(lat2);
  40. var b = Math.cos(lat1) * Math.sin(lat2) -
  41. Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
  42. return radiansToDegrees(Math.atan2(a, b));
  43. }
  44. /**
  45. * Calculates Final Bearing
  46. *
  47. * @private
  48. * @param {Coord} start starting Point
  49. * @param {Coord} end ending Point
  50. * @returns {number} bearing
  51. */
  52. function calculateFinalBearing(start, end) {
  53. // Swap start & end
  54. var bear = bearing(end, start);
  55. bear = (bear + 180) % 360;
  56. return bear;
  57. }