index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // index.ts
  2. import { convex } from "@turf/convex";
  3. import { centroid } from "@turf/centroid";
  4. import { point } from "@turf/helpers";
  5. import { getType, getCoord } from "@turf/invariant";
  6. import { coordEach } from "@turf/meta";
  7. function centerOfMass(geojson, options = {}) {
  8. switch (getType(geojson)) {
  9. case "Point":
  10. return point(getCoord(geojson), options.properties);
  11. case "Polygon":
  12. var coords = [];
  13. coordEach(geojson, function(coord) {
  14. coords.push(coord);
  15. });
  16. var centre = centroid(geojson, { properties: options.properties });
  17. var translation = centre.geometry.coordinates;
  18. var sx = 0;
  19. var sy = 0;
  20. var sArea = 0;
  21. var i, pi, pj, xi, xj, yi, yj, a;
  22. var neutralizedPoints = coords.map(function(point2) {
  23. return [point2[0] - translation[0], point2[1] - translation[1]];
  24. });
  25. for (i = 0; i < coords.length - 1; i++) {
  26. pi = neutralizedPoints[i];
  27. xi = pi[0];
  28. yi = pi[1];
  29. pj = neutralizedPoints[i + 1];
  30. xj = pj[0];
  31. yj = pj[1];
  32. a = xi * yj - xj * yi;
  33. sArea += a;
  34. sx += (xi + xj) * a;
  35. sy += (yi + yj) * a;
  36. }
  37. if (sArea === 0) {
  38. return centre;
  39. } else {
  40. var area = sArea * 0.5;
  41. var areaFactor = 1 / (6 * area);
  42. return point(
  43. [translation[0] + areaFactor * sx, translation[1] + areaFactor * sy],
  44. options.properties
  45. );
  46. }
  47. default:
  48. var hull = convex(geojson);
  49. if (hull) return centerOfMass(hull, { properties: options.properties });
  50. else return centroid(geojson, { properties: options.properties });
  51. }
  52. }
  53. var turf_center_of_mass_default = centerOfMass;
  54. export {
  55. centerOfMass,
  56. turf_center_of_mass_default as default
  57. };
  58. //# sourceMappingURL=index.js.map