index.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. var center_mean_1 = __importDefault(require("@turf/center-mean"));
  7. var distance_1 = __importDefault(require("@turf/distance"));
  8. var centroid_1 = __importDefault(require("@turf/centroid"));
  9. var helpers_1 = require("@turf/helpers");
  10. var meta_1 = require("@turf/meta");
  11. /**
  12. * Takes a {@link FeatureCollection} of points and calculates the median center,
  13. * algorithimically. The median center is understood as the point that is
  14. * requires the least total travel from all other points.
  15. *
  16. * Turfjs has four different functions for calculating the center of a set of
  17. * data. Each is useful depending on circumstance.
  18. *
  19. * `@turf/center` finds the simple center of a dataset, by finding the
  20. * midpoint between the extents of the data. That is, it divides in half the
  21. * farthest east and farthest west point as well as the farthest north and
  22. * farthest south.
  23. *
  24. * `@turf/center-of-mass` imagines that the dataset is a sheet of paper.
  25. * The center of mass is where the sheet would balance on a fingertip.
  26. *
  27. * `@turf/center-mean` takes the averages of all the coordinates and
  28. * produces a value that respects that. Unlike `@turf/center`, it is
  29. * sensitive to clusters and outliers. It lands in the statistical middle of a
  30. * dataset, not the geographical. It can also be weighted, meaning certain
  31. * points are more important than others.
  32. *
  33. * `@turf/center-median` takes the mean center and tries to find, iteratively,
  34. * a new point that requires the least amount of travel from all the points in
  35. * the dataset. It is not as sensitive to outliers as `@turf/center-mean`, but it is
  36. * attracted to clustered data. It, too, can be weighted.
  37. *
  38. * **Bibliography**
  39. *
  40. * Harold W. Kuhn and Robert E. Kuenne, “An Efficient Algorithm for the
  41. * Numerical Solution of the Generalized Weber Problem in Spatial
  42. * Economics,” _Journal of Regional Science_ 4, no. 2 (1962): 21–33,
  43. * doi:{@link https://doi.org/10.1111/j.1467-9787.1962.tb00902.x}.
  44. *
  45. * James E. Burt, Gerald M. Barber, and David L. Rigby, _Elementary
  46. * Statistics for Geographers_, 3rd ed., New York: The Guilford
  47. * Press, 2009, 150–151.
  48. *
  49. * @name centerMedian
  50. * @param {FeatureCollection<any>} features Any GeoJSON Feature Collection
  51. * @param {Object} [options={}] Optional parameters
  52. * @param {string} [options.weight] the property name used to weight the center
  53. * @param {number} [options.tolerance=0.001] the difference in distance between candidate medians at which point the algorighim stops iterating.
  54. * @param {number} [options.counter=10] how many attempts to find the median, should the tolerance be insufficient.
  55. * @returns {Feature<Point>} The median center of the collection
  56. * @example
  57. * var points = turf.points([[0, 0], [1, 0], [0, 1], [5, 8]]);
  58. * var medianCenter = turf.centerMedian(points);
  59. *
  60. * //addToMap
  61. * var addToMap = [points, medianCenter]
  62. */
  63. function centerMedian(features, options) {
  64. if (options === void 0) { options = {}; }
  65. // Optional params
  66. options = options || {};
  67. if (!helpers_1.isObject(options))
  68. throw new Error("options is invalid");
  69. var counter = options.counter || 10;
  70. if (!helpers_1.isNumber(counter))
  71. throw new Error("counter must be a number");
  72. var weightTerm = options.weight;
  73. // Calculate mean center:
  74. var meanCenter = center_mean_1.default(features, { weight: options.weight });
  75. // Calculate center of every feature:
  76. var centroids = helpers_1.featureCollection([]);
  77. meta_1.featureEach(features, function (feature) {
  78. var _a;
  79. centroids.features.push(centroid_1.default(feature, {
  80. properties: { weight: (_a = feature.properties) === null || _a === void 0 ? void 0 : _a[weightTerm] },
  81. }));
  82. });
  83. var properties = {
  84. tolerance: options.tolerance,
  85. medianCandidates: [],
  86. };
  87. return findMedian(meanCenter.geometry.coordinates, [0, 0], centroids, properties, counter);
  88. }
  89. /**
  90. * Recursive function to find new candidate medians.
  91. *
  92. * @private
  93. * @param {Position} candidateMedian current candidate median
  94. * @param {Position} previousCandidate the previous candidate median
  95. * @param {FeatureCollection<Point>} centroids the collection of centroids whose median we are determining
  96. * @param {number} counter how many attempts to try before quitting.
  97. * @returns {Feature<Point>} the median center of the dataset.
  98. */
  99. function findMedian(candidateMedian, previousCandidate, centroids, properties, counter) {
  100. var tolerance = properties.tolerance || 0.001;
  101. var candidateXsum = 0;
  102. var candidateYsum = 0;
  103. var kSum = 0;
  104. var centroidCount = 0;
  105. meta_1.featureEach(centroids, function (theCentroid) {
  106. var _a;
  107. var weightValue = (_a = theCentroid.properties) === null || _a === void 0 ? void 0 : _a.weight;
  108. var weight = weightValue === undefined || weightValue === null ? 1 : weightValue;
  109. weight = Number(weight);
  110. if (!helpers_1.isNumber(weight))
  111. throw new Error("weight value must be a number");
  112. if (weight > 0) {
  113. centroidCount += 1;
  114. var distanceFromCandidate = weight * distance_1.default(theCentroid, candidateMedian);
  115. if (distanceFromCandidate === 0)
  116. distanceFromCandidate = 1;
  117. var k = weight / distanceFromCandidate;
  118. candidateXsum += theCentroid.geometry.coordinates[0] * k;
  119. candidateYsum += theCentroid.geometry.coordinates[1] * k;
  120. kSum += k;
  121. }
  122. });
  123. if (centroidCount < 1)
  124. throw new Error("no features to measure");
  125. var candidateX = candidateXsum / kSum;
  126. var candidateY = candidateYsum / kSum;
  127. if (centroidCount === 1 ||
  128. counter === 0 ||
  129. (Math.abs(candidateX - previousCandidate[0]) < tolerance &&
  130. Math.abs(candidateY - previousCandidate[1]) < tolerance)) {
  131. return helpers_1.point([candidateX, candidateY], {
  132. medianCandidates: properties.medianCandidates,
  133. });
  134. }
  135. else {
  136. properties.medianCandidates.push([candidateX, candidateY]);
  137. return findMedian([candidateX, candidateY], candidateMedian, centroids, properties, counter - 1);
  138. }
  139. }
  140. exports.default = centerMedian;