index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { featureEach } from "@turf/meta";
  2. import { featureCollection } from "@turf/helpers";
  3. /**
  4. * Get Cluster
  5. *
  6. * @name getCluster
  7. * @param {FeatureCollection} geojson GeoJSON Features
  8. * @param {*} filter Filter used on GeoJSON properties to get Cluster
  9. * @returns {FeatureCollection} Single Cluster filtered by GeoJSON Properties
  10. * @example
  11. * var geojson = turf.featureCollection([
  12. * turf.point([0, 0], {'marker-symbol': 'circle'}),
  13. * turf.point([2, 4], {'marker-symbol': 'star'}),
  14. * turf.point([3, 6], {'marker-symbol': 'star'}),
  15. * turf.point([5, 1], {'marker-symbol': 'square'}),
  16. * turf.point([4, 2], {'marker-symbol': 'circle'})
  17. * ]);
  18. *
  19. * // Create a cluster using K-Means (adds `cluster` to GeoJSON properties)
  20. * var clustered = turf.clustersKmeans(geojson);
  21. *
  22. * // Retrieve first cluster (0)
  23. * var cluster = turf.getCluster(clustered, {cluster: 0});
  24. * //= cluster
  25. *
  26. * // Retrieve cluster based on custom properties
  27. * turf.getCluster(clustered, {'marker-symbol': 'circle'}).length;
  28. * //= 2
  29. * turf.getCluster(clustered, {'marker-symbol': 'square'}).length;
  30. * //= 1
  31. */
  32. export function getCluster(geojson, filter) {
  33. // Validation
  34. if (!geojson)
  35. throw new Error("geojson is required");
  36. if (geojson.type !== "FeatureCollection")
  37. throw new Error("geojson must be a FeatureCollection");
  38. if (filter === undefined || filter === null)
  39. throw new Error("filter is required");
  40. // Filter Features
  41. var features = [];
  42. featureEach(geojson, function (feature) {
  43. if (applyFilter(feature.properties, filter))
  44. features.push(feature);
  45. });
  46. return featureCollection(features);
  47. }
  48. /**
  49. * Callback for clusterEach
  50. *
  51. * @callback clusterEachCallback
  52. * @param {FeatureCollection} [cluster] The current cluster being processed.
  53. * @param {*} [clusterValue] Value used to create cluster being processed.
  54. * @param {number} [currentIndex] The index of the current element being processed in the array.Starts at index 0
  55. * @returns {void}
  56. */
  57. /**
  58. * clusterEach
  59. *
  60. * @name clusterEach
  61. * @param {FeatureCollection} geojson GeoJSON Features
  62. * @param {string|number} property GeoJSON property key/value used to create clusters
  63. * @param {Function} callback a method that takes (cluster, clusterValue, currentIndex)
  64. * @returns {void}
  65. * @example
  66. * var geojson = turf.featureCollection([
  67. * turf.point([0, 0]),
  68. * turf.point([2, 4]),
  69. * turf.point([3, 6]),
  70. * turf.point([5, 1]),
  71. * turf.point([4, 2])
  72. * ]);
  73. *
  74. * // Create a cluster using K-Means (adds `cluster` to GeoJSON properties)
  75. * var clustered = turf.clustersKmeans(geojson);
  76. *
  77. * // Iterate over each cluster
  78. * turf.clusterEach(clustered, 'cluster', function (cluster, clusterValue, currentIndex) {
  79. * //= cluster
  80. * //= clusterValue
  81. * //= currentIndex
  82. * })
  83. *
  84. * // Calculate the total number of clusters
  85. * var total = 0
  86. * turf.clusterEach(clustered, 'cluster', function () {
  87. * total++;
  88. * });
  89. *
  90. * // Create an Array of all the values retrieved from the 'cluster' property
  91. * var values = []
  92. * turf.clusterEach(clustered, 'cluster', function (cluster, clusterValue) {
  93. * values.push(clusterValue);
  94. * });
  95. */
  96. export function clusterEach(geojson, property, callback) {
  97. // Validation
  98. if (!geojson)
  99. throw new Error("geojson is required");
  100. if (geojson.type !== "FeatureCollection")
  101. throw new Error("geojson must be a FeatureCollection");
  102. if (property === undefined || property === null)
  103. throw new Error("property is required");
  104. // Create clusters based on property values
  105. var bins = createBins(geojson, property);
  106. var values = Object.keys(bins);
  107. for (var index = 0; index < values.length; index++) {
  108. var value = values[index];
  109. var bin = bins[value];
  110. var features = [];
  111. for (var i = 0; i < bin.length; i++) {
  112. features.push(geojson.features[bin[i]]);
  113. }
  114. callback(featureCollection(features), value, index);
  115. }
  116. }
  117. /**
  118. * Callback for clusterReduce
  119. *
  120. * The first time the callback function is called, the values provided as arguments depend
  121. * on whether the reduce method has an initialValue argument.
  122. *
  123. * If an initialValue is provided to the reduce method:
  124. * - The previousValue argument is initialValue.
  125. * - The currentValue argument is the value of the first element present in the array.
  126. *
  127. * If an initialValue is not provided:
  128. * - The previousValue argument is the value of the first element present in the array.
  129. * - The currentValue argument is the value of the second element present in the array.
  130. *
  131. * @callback clusterReduceCallback
  132. * @param {*} [previousValue] The accumulated value previously returned in the last invocation
  133. * of the callback, or initialValue, if supplied.
  134. * @param {FeatureCollection} [cluster] The current cluster being processed.
  135. * @param {*} [clusterValue] Value used to create cluster being processed.
  136. * @param {number} [currentIndex] The index of the current element being processed in the
  137. * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
  138. */
  139. /**
  140. * Reduce clusters in GeoJSON Features, similar to Array.reduce()
  141. *
  142. * @name clusterReduce
  143. * @param {FeatureCollection} geojson GeoJSON Features
  144. * @param {string|number} property GeoJSON property key/value used to create clusters
  145. * @param {Function} callback a method that takes (previousValue, cluster, clusterValue, currentIndex)
  146. * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
  147. * @returns {*} The value that results from the reduction.
  148. * @example
  149. * var geojson = turf.featureCollection([
  150. * turf.point([0, 0]),
  151. * turf.point([2, 4]),
  152. * turf.point([3, 6]),
  153. * turf.point([5, 1]),
  154. * turf.point([4, 2])
  155. * ]);
  156. *
  157. * // Create a cluster using K-Means (adds `cluster` to GeoJSON properties)
  158. * var clustered = turf.clustersKmeans(geojson);
  159. *
  160. * // Iterate over each cluster and perform a calculation
  161. * var initialValue = 0
  162. * turf.clusterReduce(clustered, 'cluster', function (previousValue, cluster, clusterValue, currentIndex) {
  163. * //=previousValue
  164. * //=cluster
  165. * //=clusterValue
  166. * //=currentIndex
  167. * return previousValue++;
  168. * }, initialValue);
  169. *
  170. * // Calculate the total number of clusters
  171. * var total = turf.clusterReduce(clustered, 'cluster', function (previousValue) {
  172. * return previousValue++;
  173. * }, 0);
  174. *
  175. * // Create an Array of all the values retrieved from the 'cluster' property
  176. * var values = turf.clusterReduce(clustered, 'cluster', function (previousValue, cluster, clusterValue) {
  177. * return previousValue.concat(clusterValue);
  178. * }, []);
  179. */
  180. export function clusterReduce(geojson, property, callback, initialValue) {
  181. var previousValue = initialValue;
  182. clusterEach(geojson, property, function (cluster, clusterValue, currentIndex) {
  183. if (currentIndex === 0 && initialValue === undefined)
  184. previousValue = cluster;
  185. else
  186. previousValue = callback(previousValue, cluster, clusterValue, currentIndex);
  187. });
  188. return previousValue;
  189. }
  190. /**
  191. * Create Bins
  192. *
  193. * @private
  194. * @param {FeatureCollection} geojson GeoJSON Features
  195. * @param {string|number} property Property values are used to create bins
  196. * @returns {Object} bins with Feature IDs
  197. * @example
  198. * var geojson = turf.featureCollection([
  199. * turf.point([0, 0], {cluster: 0, foo: 'null'}),
  200. * turf.point([2, 4], {cluster: 1, foo: 'bar'}),
  201. * turf.point([5, 1], {0: 'foo'}),
  202. * turf.point([3, 6], {cluster: 1}),
  203. * ]);
  204. * createBins(geojson, 'cluster');
  205. * //= { '0': [ 0 ], '1': [ 1, 3 ] }
  206. */
  207. export function createBins(geojson, property) {
  208. var bins = {};
  209. featureEach(geojson, function (feature, i) {
  210. var properties = feature.properties || {};
  211. if (Object.prototype.hasOwnProperty.call(properties, String(property))) {
  212. var value = properties[property];
  213. if (Object.prototype.hasOwnProperty.call(bins, value))
  214. bins[value].push(i);
  215. else
  216. bins[value] = [i];
  217. }
  218. });
  219. return bins;
  220. }
  221. /**
  222. * Apply Filter
  223. *
  224. * @private
  225. * @param {*} properties Properties
  226. * @param {*} filter Filter
  227. * @returns {boolean} applied Filter to properties
  228. */
  229. export function applyFilter(properties, filter) {
  230. if (properties === undefined)
  231. return false;
  232. var filterType = typeof filter;
  233. // String & Number
  234. if (filterType === "number" || filterType === "string")
  235. return Object.prototype.hasOwnProperty.call(properties, filter);
  236. // Array
  237. else if (Array.isArray(filter)) {
  238. for (var i = 0; i < filter.length; i++) {
  239. if (!applyFilter(properties, filter[i]))
  240. return false;
  241. }
  242. return true;
  243. // Object
  244. }
  245. else {
  246. return propertiesContainsFilter(properties, filter);
  247. }
  248. }
  249. /**
  250. * Properties contains filter (does not apply deepEqual operations)
  251. *
  252. * @private
  253. * @param {*} properties Properties
  254. * @param {Object} filter Filter
  255. * @returns {boolean} does filter equal Properties
  256. * @example
  257. * propertiesContainsFilter({foo: 'bar', cluster: 0}, {cluster: 0})
  258. * //= true
  259. * propertiesContainsFilter({foo: 'bar', cluster: 0}, {cluster: 1})
  260. * //= false
  261. */
  262. export function propertiesContainsFilter(properties, filter) {
  263. var keys = Object.keys(filter);
  264. for (var i = 0; i < keys.length; i++) {
  265. var key = keys[i];
  266. if (properties[key] !== filter[key])
  267. return false;
  268. }
  269. return true;
  270. }
  271. /**
  272. * Filter Properties
  273. *
  274. * @private
  275. * @param {*} properties Properties
  276. * @param {Array<string>} keys Used to filter Properties
  277. * @returns {*} filtered Properties
  278. * @example
  279. * filterProperties({foo: 'bar', cluster: 0}, ['cluster'])
  280. * //= {cluster: 0}
  281. */
  282. export function filterProperties(properties, keys) {
  283. if (!keys)
  284. return {};
  285. if (!keys.length)
  286. return {};
  287. var newProperties = {};
  288. for (var i = 0; i < keys.length; i++) {
  289. var key = keys[i];
  290. if (Object.prototype.hasOwnProperty.call(properties, key))
  291. newProperties[key] = properties[key];
  292. }
  293. return newProperties;
  294. }