index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { geomEach, coordEach } from "@turf/meta";
  2. import { isNumber, point, } from "@turf/helpers";
  3. /**
  4. * Takes a {@link Feature} or {@link FeatureCollection} and returns the mean center. Can be weighted.
  5. *
  6. * @name centerMean
  7. * @param {GeoJSON} geojson GeoJSON to be centered
  8. * @param {Object} [options={}] Optional parameters
  9. * @param {Object} [options.properties={}] Translate GeoJSON Properties to Point
  10. * @param {Object} [options.bbox={}] Translate GeoJSON BBox to Point
  11. * @param {Object} [options.id={}] Translate GeoJSON Id to Point
  12. * @param {string} [options.weight] the property name used to weight the center
  13. * @returns {Feature<Point>} a Point feature at the mean center point of all input features
  14. * @example
  15. * var features = turf.featureCollection([
  16. * turf.point([-97.522259, 35.4691], {value: 10}),
  17. * turf.point([-97.502754, 35.463455], {value: 3}),
  18. * turf.point([-97.508269, 35.463245], {value: 5})
  19. * ]);
  20. *
  21. * var options = {weight: "value"}
  22. * var mean = turf.centerMean(features, options);
  23. *
  24. * //addToMap
  25. * var addToMap = [features, mean]
  26. * mean.properties['marker-size'] = 'large';
  27. * mean.properties['marker-color'] = '#000';
  28. */
  29. function centerMean(geojson, // To-Do include Typescript AllGeoJSON
  30. options) {
  31. if (options === void 0) { options = {}; }
  32. var sumXs = 0;
  33. var sumYs = 0;
  34. var sumNs = 0;
  35. geomEach(geojson, function (geom, featureIndex, properties) {
  36. var weight = options.weight ? properties === null || properties === void 0 ? void 0 : properties[options.weight] : undefined;
  37. weight = weight === undefined || weight === null ? 1 : weight;
  38. if (!isNumber(weight))
  39. throw new Error("weight value must be a number for feature index " + featureIndex);
  40. weight = Number(weight);
  41. if (weight > 0) {
  42. coordEach(geom, function (coord) {
  43. sumXs += coord[0] * weight;
  44. sumYs += coord[1] * weight;
  45. sumNs += weight;
  46. });
  47. }
  48. });
  49. return point([sumXs / sumNs, sumYs / sumNs], options.properties, options);
  50. }
  51. export default centerMean;