index.js 2.3 KB

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