Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

759 řádky
26 KiB

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Supercluster = factory());
  5. })(this, (function () { 'use strict';
  6. const ARRAY_TYPES = [
  7. Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
  8. Int32Array, Uint32Array, Float32Array, Float64Array
  9. ];
  10. /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
  11. const VERSION = 1; // serialized format version
  12. const HEADER_SIZE = 8;
  13. class KDBush {
  14. /**
  15. * Creates an index from raw `ArrayBuffer` data.
  16. * @param {ArrayBuffer} data
  17. */
  18. static from(data) {
  19. if (!(data instanceof ArrayBuffer)) {
  20. throw new Error('Data must be an instance of ArrayBuffer.');
  21. }
  22. const [magic, versionAndType] = new Uint8Array(data, 0, 2);
  23. if (magic !== 0xdb) {
  24. throw new Error('Data does not appear to be in a KDBush format.');
  25. }
  26. const version = versionAndType >> 4;
  27. if (version !== VERSION) {
  28. throw new Error(`Got v${version} data when expected v${VERSION}.`);
  29. }
  30. const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
  31. if (!ArrayType) {
  32. throw new Error('Unrecognized array type.');
  33. }
  34. const [nodeSize] = new Uint16Array(data, 2, 1);
  35. const [numItems] = new Uint32Array(data, 4, 1);
  36. return new KDBush(numItems, nodeSize, ArrayType, data);
  37. }
  38. /**
  39. * Creates an index that will hold a given number of items.
  40. * @param {number} numItems
  41. * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
  42. * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
  43. * @param {ArrayBuffer} [data] (For internal use only)
  44. */
  45. constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
  46. if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);
  47. this.numItems = +numItems;
  48. this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
  49. this.ArrayType = ArrayType;
  50. this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
  51. const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
  52. const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
  53. const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
  54. const padCoords = (8 - idsByteSize % 8) % 8;
  55. if (arrayTypeIndex < 0) {
  56. throw new Error(`Unexpected typed array class: ${ArrayType}.`);
  57. }
  58. if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer
  59. this.data = data;
  60. this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
  61. this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  62. this._pos = numItems * 2;
  63. this._finished = true;
  64. } else { // initialize a new index
  65. this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
  66. this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
  67. this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  68. this._pos = 0;
  69. this._finished = false;
  70. // set header
  71. new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);
  72. new Uint16Array(this.data, 2, 1)[0] = nodeSize;
  73. new Uint32Array(this.data, 4, 1)[0] = numItems;
  74. }
  75. }
  76. /**
  77. * Add a point to the index.
  78. * @param {number} x
  79. * @param {number} y
  80. * @returns {number} An incremental index associated with the added item (starting from `0`).
  81. */
  82. add(x, y) {
  83. const index = this._pos >> 1;
  84. this.ids[index] = index;
  85. this.coords[this._pos++] = x;
  86. this.coords[this._pos++] = y;
  87. return index;
  88. }
  89. /**
  90. * Perform indexing of the added points.
  91. */
  92. finish() {
  93. const numAdded = this._pos >> 1;
  94. if (numAdded !== this.numItems) {
  95. throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
  96. }
  97. // kd-sort both arrays for efficient search
  98. sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
  99. this._finished = true;
  100. return this;
  101. }
  102. /**
  103. * Search the index for items within a given bounding box.
  104. * @param {number} minX
  105. * @param {number} minY
  106. * @param {number} maxX
  107. * @param {number} maxY
  108. * @returns {number[]} An array of indices correponding to the found items.
  109. */
  110. range(minX, minY, maxX, maxY) {
  111. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  112. const {ids, coords, nodeSize} = this;
  113. const stack = [0, ids.length - 1, 0];
  114. const result = [];
  115. // recursively search for items in range in the kd-sorted arrays
  116. while (stack.length) {
  117. const axis = stack.pop() || 0;
  118. const right = stack.pop() || 0;
  119. const left = stack.pop() || 0;
  120. // if we reached "tree node", search linearly
  121. if (right - left <= nodeSize) {
  122. for (let i = left; i <= right; i++) {
  123. const x = coords[2 * i];
  124. const y = coords[2 * i + 1];
  125. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
  126. }
  127. continue;
  128. }
  129. // otherwise find the middle index
  130. const m = (left + right) >> 1;
  131. // include the middle item if it's in range
  132. const x = coords[2 * m];
  133. const y = coords[2 * m + 1];
  134. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
  135. // queue search in halves that intersect the query
  136. if (axis === 0 ? minX <= x : minY <= y) {
  137. stack.push(left);
  138. stack.push(m - 1);
  139. stack.push(1 - axis);
  140. }
  141. if (axis === 0 ? maxX >= x : maxY >= y) {
  142. stack.push(m + 1);
  143. stack.push(right);
  144. stack.push(1 - axis);
  145. }
  146. }
  147. return result;
  148. }
  149. /**
  150. * Search the index for items within a given radius.
  151. * @param {number} qx
  152. * @param {number} qy
  153. * @param {number} r Query radius.
  154. * @returns {number[]} An array of indices correponding to the found items.
  155. */
  156. within(qx, qy, r) {
  157. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  158. const {ids, coords, nodeSize} = this;
  159. const stack = [0, ids.length - 1, 0];
  160. const result = [];
  161. const r2 = r * r;
  162. // recursively search for items within radius in the kd-sorted arrays
  163. while (stack.length) {
  164. const axis = stack.pop() || 0;
  165. const right = stack.pop() || 0;
  166. const left = stack.pop() || 0;
  167. // if we reached "tree node", search linearly
  168. if (right - left <= nodeSize) {
  169. for (let i = left; i <= right; i++) {
  170. if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);
  171. }
  172. continue;
  173. }
  174. // otherwise find the middle index
  175. const m = (left + right) >> 1;
  176. // include the middle item if it's in range
  177. const x = coords[2 * m];
  178. const y = coords[2 * m + 1];
  179. if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);
  180. // queue search in halves that intersect the query
  181. if (axis === 0 ? qx - r <= x : qy - r <= y) {
  182. stack.push(left);
  183. stack.push(m - 1);
  184. stack.push(1 - axis);
  185. }
  186. if (axis === 0 ? qx + r >= x : qy + r >= y) {
  187. stack.push(m + 1);
  188. stack.push(right);
  189. stack.push(1 - axis);
  190. }
  191. }
  192. return result;
  193. }
  194. }
  195. /**
  196. * @param {Uint16Array | Uint32Array} ids
  197. * @param {InstanceType<TypedArrayConstructor>} coords
  198. * @param {number} nodeSize
  199. * @param {number} left
  200. * @param {number} right
  201. * @param {number} axis
  202. */
  203. function sort(ids, coords, nodeSize, left, right, axis) {
  204. if (right - left <= nodeSize) return;
  205. const m = (left + right) >> 1; // middle index
  206. // sort ids and coords around the middle index so that the halves lie
  207. // either left/right or top/bottom correspondingly (taking turns)
  208. select(ids, coords, m, left, right, axis);
  209. // recursively kd-sort first half and second half on the opposite axis
  210. sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
  211. sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
  212. }
  213. /**
  214. * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
  215. * [left..k-1] items are smaller than k-th item (on either x or y axis)
  216. * @param {Uint16Array | Uint32Array} ids
  217. * @param {InstanceType<TypedArrayConstructor>} coords
  218. * @param {number} k
  219. * @param {number} left
  220. * @param {number} right
  221. * @param {number} axis
  222. */
  223. function select(ids, coords, k, left, right, axis) {
  224. while (right > left) {
  225. if (right - left > 600) {
  226. const n = right - left + 1;
  227. const m = k - left + 1;
  228. const z = Math.log(n);
  229. const s = 0.5 * Math.exp(2 * z / 3);
  230. const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  231. const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  232. const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  233. select(ids, coords, k, newLeft, newRight, axis);
  234. }
  235. const t = coords[2 * k + axis];
  236. let i = left;
  237. let j = right;
  238. swapItem(ids, coords, left, k);
  239. if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
  240. while (i < j) {
  241. swapItem(ids, coords, i, j);
  242. i++;
  243. j--;
  244. while (coords[2 * i + axis] < t) i++;
  245. while (coords[2 * j + axis] > t) j--;
  246. }
  247. if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
  248. else {
  249. j++;
  250. swapItem(ids, coords, j, right);
  251. }
  252. if (j <= k) left = j + 1;
  253. if (k <= j) right = j - 1;
  254. }
  255. }
  256. /**
  257. * @param {Uint16Array | Uint32Array} ids
  258. * @param {InstanceType<TypedArrayConstructor>} coords
  259. * @param {number} i
  260. * @param {number} j
  261. */
  262. function swapItem(ids, coords, i, j) {
  263. swap(ids, i, j);
  264. swap(coords, 2 * i, 2 * j);
  265. swap(coords, 2 * i + 1, 2 * j + 1);
  266. }
  267. /**
  268. * @param {InstanceType<TypedArrayConstructor>} arr
  269. * @param {number} i
  270. * @param {number} j
  271. */
  272. function swap(arr, i, j) {
  273. const tmp = arr[i];
  274. arr[i] = arr[j];
  275. arr[j] = tmp;
  276. }
  277. /**
  278. * @param {number} ax
  279. * @param {number} ay
  280. * @param {number} bx
  281. * @param {number} by
  282. */
  283. function sqDist(ax, ay, bx, by) {
  284. const dx = ax - bx;
  285. const dy = ay - by;
  286. return dx * dx + dy * dy;
  287. }
  288. const defaultOptions = {
  289. minZoom: 0, // min zoom to generate clusters on
  290. maxZoom: 16, // max zoom level to cluster the points on
  291. minPoints: 2, // minimum points to form a cluster
  292. radius: 40, // cluster radius in pixels
  293. extent: 512, // tile extent (radius is calculated relative to it)
  294. nodeSize: 64, // size of the KD-tree leaf node, affects performance
  295. log: false, // whether to log timing info
  296. // whether to generate numeric ids for input features (in vector tiles)
  297. generateId: false,
  298. // a reduce function for calculating custom cluster properties
  299. reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; }
  300. // properties to use for individual points when running the reducer
  301. map: props => props // props => ({sum: props.my_value})
  302. };
  303. const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1));
  304. const OFFSET_ZOOM = 2;
  305. const OFFSET_ID = 3;
  306. const OFFSET_PARENT = 4;
  307. const OFFSET_NUM = 5;
  308. const OFFSET_PROP = 6;
  309. class Supercluster {
  310. constructor(options) {
  311. this.options = Object.assign(Object.create(defaultOptions), options);
  312. this.trees = new Array(this.options.maxZoom + 1);
  313. this.stride = this.options.reduce ? 7 : 6;
  314. this.clusterProps = [];
  315. }
  316. load(points) {
  317. const {log, minZoom, maxZoom} = this.options;
  318. if (log) console.time('total time');
  319. const timerId = `prepare ${ points.length } points`;
  320. if (log) console.time(timerId);
  321. this.points = points;
  322. // generate a cluster object for each point and index input points into a KD-tree
  323. const data = [];
  324. for (let i = 0; i < points.length; i++) {
  325. const p = points[i];
  326. if (!p.geometry) continue;
  327. const [lng, lat] = p.geometry.coordinates;
  328. const x = fround(lngX(lng));
  329. const y = fround(latY(lat));
  330. // store internal point/cluster data in flat numeric arrays for performance
  331. data.push(
  332. x, y, // projected point coordinates
  333. Infinity, // the last zoom the point was processed at
  334. i, // index of the source feature in the original input array
  335. -1, // parent cluster id
  336. 1 // number of points in a cluster
  337. );
  338. if (this.options.reduce) data.push(0); // noop
  339. }
  340. let tree = this.trees[maxZoom + 1] = this._createTree(data);
  341. if (log) console.timeEnd(timerId);
  342. // cluster points on max zoom, then cluster the results on previous zoom, etc.;
  343. // results in a cluster hierarchy across zoom levels
  344. for (let z = maxZoom; z >= minZoom; z--) {
  345. const now = +Date.now();
  346. // create a new set of clusters for the zoom and index them with a KD-tree
  347. tree = this.trees[z] = this._createTree(this._cluster(tree, z));
  348. if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now);
  349. }
  350. if (log) console.timeEnd('total time');
  351. return this;
  352. }
  353. getClusters(bbox, zoom) {
  354. let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
  355. const minLat = Math.max(-90, Math.min(90, bbox[1]));
  356. let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
  357. const maxLat = Math.max(-90, Math.min(90, bbox[3]));
  358. if (bbox[2] - bbox[0] >= 360) {
  359. minLng = -180;
  360. maxLng = 180;
  361. } else if (minLng > maxLng) {
  362. const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom);
  363. const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom);
  364. return easternHem.concat(westernHem);
  365. }
  366. const tree = this.trees[this._limitZoom(zoom)];
  367. const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));
  368. const data = tree.data;
  369. const clusters = [];
  370. for (const id of ids) {
  371. const k = this.stride * id;
  372. clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
  373. }
  374. return clusters;
  375. }
  376. getChildren(clusterId) {
  377. const originId = this._getOriginId(clusterId);
  378. const originZoom = this._getOriginZoom(clusterId);
  379. const errorMsg = 'No cluster with the specified id.';
  380. const tree = this.trees[originZoom];
  381. if (!tree) throw new Error(errorMsg);
  382. const data = tree.data;
  383. if (originId * this.stride >= data.length) throw new Error(errorMsg);
  384. const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
  385. const x = data[originId * this.stride];
  386. const y = data[originId * this.stride + 1];
  387. const ids = tree.within(x, y, r);
  388. const children = [];
  389. for (const id of ids) {
  390. const k = id * this.stride;
  391. if (data[k + OFFSET_PARENT] === clusterId) {
  392. children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
  393. }
  394. }
  395. if (children.length === 0) throw new Error(errorMsg);
  396. return children;
  397. }
  398. getLeaves(clusterId, limit, offset) {
  399. limit = limit || 10;
  400. offset = offset || 0;
  401. const leaves = [];
  402. this._appendLeaves(leaves, clusterId, limit, offset, 0);
  403. return leaves;
  404. }
  405. getTile(z, x, y) {
  406. const tree = this.trees[this._limitZoom(z)];
  407. const z2 = Math.pow(2, z);
  408. const {extent, radius} = this.options;
  409. const p = radius / extent;
  410. const top = (y - p) / z2;
  411. const bottom = (y + 1 + p) / z2;
  412. const tile = {
  413. features: []
  414. };
  415. this._addTileFeatures(
  416. tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom),
  417. tree.data, x, y, z2, tile);
  418. if (x === 0) {
  419. this._addTileFeatures(
  420. tree.range(1 - p / z2, top, 1, bottom),
  421. tree.data, z2, y, z2, tile);
  422. }
  423. if (x === z2 - 1) {
  424. this._addTileFeatures(
  425. tree.range(0, top, p / z2, bottom),
  426. tree.data, -1, y, z2, tile);
  427. }
  428. return tile.features.length ? tile : null;
  429. }
  430. getClusterExpansionZoom(clusterId) {
  431. let expansionZoom = this._getOriginZoom(clusterId) - 1;
  432. while (expansionZoom <= this.options.maxZoom) {
  433. const children = this.getChildren(clusterId);
  434. expansionZoom++;
  435. if (children.length !== 1) break;
  436. clusterId = children[0].properties.cluster_id;
  437. }
  438. return expansionZoom;
  439. }
  440. _appendLeaves(result, clusterId, limit, offset, skipped) {
  441. const children = this.getChildren(clusterId);
  442. for (const child of children) {
  443. const props = child.properties;
  444. if (props && props.cluster) {
  445. if (skipped + props.point_count <= offset) {
  446. // skip the whole cluster
  447. skipped += props.point_count;
  448. } else {
  449. // enter the cluster
  450. skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);
  451. // exit the cluster
  452. }
  453. } else if (skipped < offset) {
  454. // skip a single point
  455. skipped++;
  456. } else {
  457. // add a single point
  458. result.push(child);
  459. }
  460. if (result.length === limit) break;
  461. }
  462. return skipped;
  463. }
  464. _createTree(data) {
  465. const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);
  466. for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]);
  467. tree.finish();
  468. tree.data = data;
  469. return tree;
  470. }
  471. _addTileFeatures(ids, data, x, y, z2, tile) {
  472. for (const i of ids) {
  473. const k = i * this.stride;
  474. const isCluster = data[k + OFFSET_NUM] > 1;
  475. let tags, px, py;
  476. if (isCluster) {
  477. tags = getClusterProperties(data, k, this.clusterProps);
  478. px = data[k];
  479. py = data[k + 1];
  480. } else {
  481. const p = this.points[data[k + OFFSET_ID]];
  482. tags = p.properties;
  483. const [lng, lat] = p.geometry.coordinates;
  484. px = lngX(lng);
  485. py = latY(lat);
  486. }
  487. const f = {
  488. type: 1,
  489. geometry: [[
  490. Math.round(this.options.extent * (px * z2 - x)),
  491. Math.round(this.options.extent * (py * z2 - y))
  492. ]],
  493. tags
  494. };
  495. // assign id
  496. let id;
  497. if (isCluster || this.options.generateId) {
  498. // optionally generate id for points
  499. id = data[k + OFFSET_ID];
  500. } else {
  501. // keep id if already assigned
  502. id = this.points[data[k + OFFSET_ID]].id;
  503. }
  504. if (id !== undefined) f.id = id;
  505. tile.features.push(f);
  506. }
  507. }
  508. _limitZoom(z) {
  509. return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));
  510. }
  511. _cluster(tree, zoom) {
  512. const {radius, extent, reduce, minPoints} = this.options;
  513. const r = radius / (extent * Math.pow(2, zoom));
  514. const data = tree.data;
  515. const nextData = [];
  516. const stride = this.stride;
  517. // loop through each point
  518. for (let i = 0; i < data.length; i += stride) {
  519. // if we've already visited the point at this zoom level, skip it
  520. if (data[i + OFFSET_ZOOM] <= zoom) continue;
  521. data[i + OFFSET_ZOOM] = zoom;
  522. // find all nearby points
  523. const x = data[i];
  524. const y = data[i + 1];
  525. const neighborIds = tree.within(data[i], data[i + 1], r);
  526. const numPointsOrigin = data[i + OFFSET_NUM];
  527. let numPoints = numPointsOrigin;
  528. // count the number of points in a potential cluster
  529. for (const neighborId of neighborIds) {
  530. const k = neighborId * stride;
  531. // filter out neighbors that are already processed
  532. if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];
  533. }
  534. // if there were neighbors to merge, and there are enough points to form a cluster
  535. if (numPoints > numPointsOrigin && numPoints >= minPoints) {
  536. let wx = x * numPointsOrigin;
  537. let wy = y * numPointsOrigin;
  538. let clusterProperties;
  539. let clusterPropIndex = -1;
  540. // encode both zoom and point index on which the cluster originated -- offset by total length of features
  541. const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;
  542. for (const neighborId of neighborIds) {
  543. const k = neighborId * stride;
  544. if (data[k + OFFSET_ZOOM] <= zoom) continue;
  545. data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice)
  546. const numPoints2 = data[k + OFFSET_NUM];
  547. wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center
  548. wy += data[k + 1] * numPoints2;
  549. data[k + OFFSET_PARENT] = id;
  550. if (reduce) {
  551. if (!clusterProperties) {
  552. clusterProperties = this._map(data, i, true);
  553. clusterPropIndex = this.clusterProps.length;
  554. this.clusterProps.push(clusterProperties);
  555. }
  556. reduce(clusterProperties, this._map(data, k));
  557. }
  558. }
  559. data[i + OFFSET_PARENT] = id;
  560. nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);
  561. if (reduce) nextData.push(clusterPropIndex);
  562. } else { // left points as unclustered
  563. for (let j = 0; j < stride; j++) nextData.push(data[i + j]);
  564. if (numPoints > 1) {
  565. for (const neighborId of neighborIds) {
  566. const k = neighborId * stride;
  567. if (data[k + OFFSET_ZOOM] <= zoom) continue;
  568. data[k + OFFSET_ZOOM] = zoom;
  569. for (let j = 0; j < stride; j++) nextData.push(data[k + j]);
  570. }
  571. }
  572. }
  573. }
  574. return nextData;
  575. }
  576. // get index of the point from which the cluster originated
  577. _getOriginId(clusterId) {
  578. return (clusterId - this.points.length) >> 5;
  579. }
  580. // get zoom of the point from which the cluster originated
  581. _getOriginZoom(clusterId) {
  582. return (clusterId - this.points.length) % 32;
  583. }
  584. _map(data, i, clone) {
  585. if (data[i + OFFSET_NUM] > 1) {
  586. const props = this.clusterProps[data[i + OFFSET_PROP]];
  587. return clone ? Object.assign({}, props) : props;
  588. }
  589. const original = this.points[data[i + OFFSET_ID]].properties;
  590. const result = this.options.map(original);
  591. return clone && result === original ? Object.assign({}, result) : result;
  592. }
  593. }
  594. function getClusterJSON(data, i, clusterProps) {
  595. return {
  596. type: 'Feature',
  597. id: data[i + OFFSET_ID],
  598. properties: getClusterProperties(data, i, clusterProps),
  599. geometry: {
  600. type: 'Point',
  601. coordinates: [xLng(data[i]), yLat(data[i + 1])]
  602. }
  603. };
  604. }
  605. function getClusterProperties(data, i, clusterProps) {
  606. const count = data[i + OFFSET_NUM];
  607. const abbrev =
  608. count >= 10000 ? `${Math.round(count / 1000) }k` :
  609. count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count;
  610. const propIndex = data[i + OFFSET_PROP];
  611. const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);
  612. return Object.assign(properties, {
  613. cluster: true,
  614. cluster_id: data[i + OFFSET_ID],
  615. point_count: count,
  616. point_count_abbreviated: abbrev
  617. });
  618. }
  619. // longitude/latitude to spherical mercator in [0..1] range
  620. function lngX(lng) {
  621. return lng / 360 + 0.5;
  622. }
  623. function latY(lat) {
  624. const sin = Math.sin(lat * Math.PI / 180);
  625. const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI);
  626. return y < 0 ? 0 : y > 1 ? 1 : y;
  627. }
  628. // spherical mercator to longitude/latitude
  629. function xLng(x) {
  630. return (x - 0.5) * 360;
  631. }
  632. function yLat(y) {
  633. const y2 = (180 - y * 360) * Math.PI / 180;
  634. return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
  635. }
  636. return Supercluster;
  637. }));