index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import bearing from "@turf/bearing";
  2. import { bearingToAzimuth, isObject } from "@turf/helpers";
  3. import rhumbBearing from "@turf/rhumb-bearing";
  4. /**
  5. * Finds the angle formed by two adjacent segments defined by 3 points. The result will be the (positive clockwise)
  6. * angle with origin on the `startPoint-midPoint` segment, or its explementary angle if required.
  7. *
  8. * @name angle
  9. * @param {Coord} startPoint Start Point Coordinates
  10. * @param {Coord} midPoint Mid Point Coordinates
  11. * @param {Coord} endPoint End Point Coordinates
  12. * @param {Object} [options={}] Optional parameters
  13. * @param {boolean} [options.explementary=false] Returns the explementary angle instead (360 - angle)
  14. * @param {boolean} [options.mercator=false] if calculations should be performed over Mercator or WGS84 projection
  15. * @returns {number} Angle between the provided points, or its explementary.
  16. * @example
  17. * turf.angle([5, 5], [5, 6], [3, 4]);
  18. * //=45
  19. */
  20. function angle(startPoint, midPoint, endPoint, options) {
  21. if (options === void 0) { options = {}; }
  22. // Optional Parameters
  23. if (!isObject(options)) {
  24. throw new Error("options is invalid");
  25. }
  26. // Validation
  27. if (!startPoint) {
  28. throw new Error("startPoint is required");
  29. }
  30. if (!midPoint) {
  31. throw new Error("midPoint is required");
  32. }
  33. if (!endPoint) {
  34. throw new Error("endPoint is required");
  35. }
  36. // Rename to shorter variables
  37. var A = startPoint;
  38. var O = midPoint;
  39. var B = endPoint;
  40. // Main
  41. var azimuthAO = bearingToAzimuth(options.mercator !== true ? bearing(A, O) : rhumbBearing(A, O));
  42. var azimuthBO = bearingToAzimuth(options.mercator !== true ? bearing(B, O) : rhumbBearing(B, O));
  43. var angleAO = Math.abs(azimuthAO - azimuthBO);
  44. // Explementary angle
  45. if (options.explementary === true) {
  46. return 360 - angleAO;
  47. }
  48. return angleAO;
  49. }
  50. export default angle;