index.js 2.1 KB

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