index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import { coordEach } from "@turf/meta";
  2. import { point } from "@turf/helpers";
  3. /**
  4. * Takes one or more features and calculates the centroid using the mean of all vertices.
  5. * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.
  6. *
  7. * @name centroid
  8. * @param {GeoJSON} geojson GeoJSON to be centered
  9. * @param {Object} [options={}] Optional Parameters
  10. * @param {Object} [options.properties={}] an Object that is used as the {@link Feature}'s properties
  11. * @returns {Feature<Point>} the centroid of the input features
  12. * @example
  13. * var polygon = turf.polygon([[[-81, 41], [-88, 36], [-84, 31], [-80, 33], [-77, 39], [-81, 41]]]);
  14. *
  15. * var centroid = turf.centroid(polygon);
  16. *
  17. * //addToMap
  18. * var addToMap = [polygon, centroid]
  19. */
  20. function centroid(geojson, options) {
  21. if (options === void 0) { options = {}; }
  22. var xSum = 0;
  23. var ySum = 0;
  24. var len = 0;
  25. coordEach(geojson, function (coord) {
  26. xSum += coord[0];
  27. ySum += coord[1];
  28. len++;
  29. }, true);
  30. return point([xSum / len, ySum / len], options.properties);
  31. }
  32. export default centroid;