index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict';
  2. var invariant = require('@turf/invariant');
  3. /**
  4. * Takes a triangular plane as a {@link Polygon}
  5. * and a {@link Point} within that triangle and returns the z-value
  6. * at that point. The Polygon should have properties `a`, `b`, and `c`
  7. * that define the values at its three corners. Alternatively, the z-values
  8. * of each triangle point can be provided by their respective 3rd coordinate
  9. * if their values are not provided as properties.
  10. *
  11. * @name planepoint
  12. * @param {Coord} point the Point for which a z-value will be calculated
  13. * @param {Feature<Polygon>} triangle a Polygon feature with three vertices
  14. * @returns {number} the z-value for `interpolatedPoint`
  15. * @example
  16. * var point = turf.point([-75.3221, 39.529]);
  17. * // "a", "b", and "c" values represent the values of the coordinates in order.
  18. * var triangle = turf.polygon([[
  19. * [-75.1221, 39.57],
  20. * [-75.58, 39.18],
  21. * [-75.97, 39.86],
  22. * [-75.1221, 39.57]
  23. * ]], {
  24. * "a": 11,
  25. * "b": 122,
  26. * "c": 44
  27. * });
  28. *
  29. * var zValue = turf.planepoint(point, triangle);
  30. * point.properties.zValue = zValue;
  31. *
  32. * //addToMap
  33. * var addToMap = [triangle, point];
  34. */
  35. function planepoint(point, triangle) {
  36. // Normalize input
  37. var coord = invariant.getCoord(point);
  38. var geom = invariant.getGeom(triangle);
  39. var coords = geom.coordinates;
  40. var outer = coords[0];
  41. if (outer.length < 4)
  42. throw new Error("OuterRing of a Polygon must have 4 or more Positions.");
  43. var properties = triangle.properties || {};
  44. var a = properties.a;
  45. var b = properties.b;
  46. var c = properties.c;
  47. // Planepoint
  48. var x = coord[0];
  49. var y = coord[1];
  50. var x1 = outer[0][0];
  51. var y1 = outer[0][1];
  52. var z1 = a !== undefined ? a : outer[0][2];
  53. var x2 = outer[1][0];
  54. var y2 = outer[1][1];
  55. var z2 = b !== undefined ? b : outer[1][2];
  56. var x3 = outer[2][0];
  57. var y3 = outer[2][1];
  58. var z3 = c !== undefined ? c : outer[2][2];
  59. var z =
  60. (z3 * (x - x1) * (y - y2) +
  61. z1 * (x - x2) * (y - y3) +
  62. z2 * (x - x3) * (y - y1) -
  63. z2 * (x - x1) * (y - y3) -
  64. z3 * (x - x2) * (y - y1) -
  65. z1 * (x - x3) * (y - y2)) /
  66. ((x - x1) * (y - y2) +
  67. (x - x2) * (y - y3) +
  68. (x - x3) * (y - y1) -
  69. (x - x1) * (y - y3) -
  70. (x - x2) * (y - y1) -
  71. (x - x3) * (y - y2));
  72. return z;
  73. }
  74. module.exports = planepoint;
  75. module.exports.default = planepoint;