MarkerClusters.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. /* *
  2. *
  3. * Marker clusters module.
  4. *
  5. * (c) 2010-2020 Torstein Honsi
  6. *
  7. * Author: Wojciech Chmiel
  8. *
  9. * License: www.highcharts.com/license
  10. *
  11. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  12. *
  13. * */
  14. 'use strict';
  15. import A from '../Core/Animation/AnimationUtilities.js';
  16. var animObject = A.animObject;
  17. import BaseSeries from '../Core/Series/Series.js';
  18. import Chart from '../Core/Chart/Chart.js';
  19. import H from '../Core/Globals.js';
  20. import O from '../Core/Options.js';
  21. var defaultOptions = O.defaultOptions;
  22. import Point from '../Core/Series/Point.js';
  23. import SVGRenderer from '../Core/Renderer/SVG/SVGRenderer.js';
  24. import U from '../Core/Utilities.js';
  25. var addEvent = U.addEvent, defined = U.defined, error = U.error, isArray = U.isArray, isFunction = U.isFunction, isObject = U.isObject, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, relativeLength = U.relativeLength, syncTimeout = U.syncTimeout;
  26. /**
  27. * Function callback when a cluster is clicked.
  28. *
  29. * @callback Highcharts.MarkerClusterDrillCallbackFunction
  30. *
  31. * @param {Highcharts.Point} this
  32. * The point where the event occured.
  33. *
  34. * @param {Highcharts.PointClickEventObject} event
  35. * Event arguments.
  36. */
  37. ''; // detach doclets from following code
  38. /* eslint-disable no-invalid-this */
  39. import Axis from '../Core/Axis/Axis.js';
  40. import '../Series/LineSeries.js';
  41. var Series = H.Series, Scatter = BaseSeries.seriesTypes.scatter, baseGeneratePoints = Series.prototype.generatePoints, stateIdCounter = 0,
  42. // Points that ids are included in the oldPointsStateId array
  43. // are hidden before animation. Other ones are destroyed.
  44. oldPointsStateId = [];
  45. /**
  46. * Options for marker clusters, the concept of sampling the data
  47. * values into larger blocks in order to ease readability and
  48. * increase performance of the JavaScript charts.
  49. *
  50. * Note: marker clusters module is not working with `boost`
  51. * and `draggable-points` modules.
  52. *
  53. * The marker clusters feature requires the marker-clusters.js
  54. * file to be loaded, found in the modules directory of the download
  55. * package, or online at [code.highcharts.com/modules/marker-clusters.js
  56. * ](code.highcharts.com/modules/marker-clusters.js).
  57. *
  58. * @sample maps/marker-clusters/europe
  59. * Maps marker clusters
  60. * @sample highcharts/marker-clusters/basic
  61. * Scatter marker clusters
  62. * @sample maps/marker-clusters/optimized-kmeans
  63. * Marker clusters with colorAxis
  64. *
  65. * @product highcharts highmaps
  66. * @since 8.0.0
  67. * @optionparent plotOptions.scatter.cluster
  68. *
  69. * @private
  70. */
  71. var clusterDefaultOptions = {
  72. /**
  73. * Whether to enable the marker-clusters module.
  74. *
  75. * @sample maps/marker-clusters/basic
  76. * Maps marker clusters
  77. * @sample highcharts/marker-clusters/basic
  78. * Scatter marker clusters
  79. */
  80. enabled: false,
  81. /**
  82. * When set to `false` prevent cluster overlapping - this option
  83. * works only when `layoutAlgorithm.type = "grid"`.
  84. *
  85. * @sample highcharts/marker-clusters/grid
  86. * Prevent overlapping
  87. */
  88. allowOverlap: true,
  89. /**
  90. * Options for the cluster marker animation.
  91. * @type {boolean|Partial<Highcharts.AnimationOptionsObject>}
  92. * @default { "duration": 500 }
  93. */
  94. animation: {
  95. /** @ignore-option */
  96. duration: 500
  97. },
  98. /**
  99. * Zoom the plot area to the cluster points range when a cluster is clicked.
  100. */
  101. drillToCluster: true,
  102. /**
  103. * The minimum amount of points to be combined into a cluster.
  104. * This value has to be greater or equal to 2.
  105. *
  106. * @sample highcharts/marker-clusters/basic
  107. * At least three points in the cluster
  108. */
  109. minimumClusterSize: 2,
  110. /**
  111. * Options for layout algorithm. Inside there
  112. * are options to change the type of the algorithm, gridSize,
  113. * distance or iterations.
  114. */
  115. layoutAlgorithm: {
  116. /**
  117. * Type of the algorithm used to combine points into a cluster.
  118. * There are three available algorithms:
  119. *
  120. * 1) `grid` - grid-based clustering technique. Points are assigned
  121. * to squares of set size depending on their position on the plot
  122. * area. Points inside the grid square are combined into a cluster.
  123. * The grid size can be controlled by `gridSize` property
  124. * (grid size changes at certain zoom levels).
  125. *
  126. * 2) `kmeans` - based on K-Means clustering technique. In the
  127. * first step, points are divided using the grid method (distance
  128. * property is a grid size) to find the initial amount of clusters.
  129. * Next, each point is classified by computing the distance between
  130. * each cluster center and that point. When the closest cluster
  131. * distance is lower than distance property set by a user the point
  132. * is added to this cluster otherwise is classified as `noise`. The
  133. * algorithm is repeated until each cluster center not change its
  134. * previous position more than one pixel. This technique is more
  135. * accurate but also more time consuming than the `grid` algorithm,
  136. * especially for big datasets.
  137. *
  138. * 3) `optimizedKmeans` - based on K-Means clustering technique. This
  139. * algorithm uses k-means algorithm only on the chart initialization
  140. * or when chart extremes have greater range than on initialization.
  141. * When a chart is redrawn the algorithm checks only clustered points
  142. * distance from the cluster center and rebuild it when the point is
  143. * spaced enough to be outside the cluster. It provides performance
  144. * improvement and more stable clusters position yet can be used rather
  145. * on small and sparse datasets.
  146. *
  147. * By default, the algorithm depends on visible quantity of points
  148. * and `kmeansThreshold`. When there are more visible points than the
  149. * `kmeansThreshold` the `grid` algorithm is used, otherwise `kmeans`.
  150. *
  151. * The custom clustering algorithm can be added by assigning a callback
  152. * function as the type property. This function takes an array of
  153. * `processedXData`, `processedYData`, `processedXData` indexes and
  154. * `layoutAlgorithm` options as arguments and should return an object
  155. * with grouped data.
  156. *
  157. * The algorithm should return an object like that:
  158. * <pre>{
  159. * clusterId1: [{
  160. * x: 573,
  161. * y: 285,
  162. * index: 1 // point index in the data array
  163. * }, {
  164. * x: 521,
  165. * y: 197,
  166. * index: 2
  167. * }],
  168. * clusterId2: [{
  169. * ...
  170. * }]
  171. * ...
  172. * }</pre>
  173. *
  174. * `clusterId` (example above - unique id of a cluster or noise)
  175. * is an array of points belonging to a cluster. If the
  176. * array has only one point or fewer points than set in
  177. * `cluster.minimumClusterSize` it won't be combined into a cluster.
  178. *
  179. * @sample maps/marker-clusters/optimized-kmeans
  180. * Optimized K-Means algorithm
  181. * @sample highcharts/marker-clusters/kmeans
  182. * K-Means algorithm
  183. * @sample highcharts/marker-clusters/grid
  184. * Grid algorithm
  185. * @sample maps/marker-clusters/custom-alg
  186. * Custom algorithm
  187. *
  188. * @type {string|Function}
  189. * @see [cluster.minimumClusterSize](#plotOptions.scatter.marker.cluster.minimumClusterSize)
  190. * @apioption plotOptions.scatter.cluster.layoutAlgorithm.type
  191. */
  192. /**
  193. * When `type` is set to the `grid`,
  194. * `gridSize` is a size of a grid square element either as a number
  195. * defining pixels, or a percentage defining a percentage
  196. * of the plot area width.
  197. *
  198. * @type {number|string}
  199. */
  200. gridSize: 50,
  201. /**
  202. * When `type` is set to `kmeans`,
  203. * `iterations` are the number of iterations that this algorithm will be
  204. * repeated to find clusters positions.
  205. *
  206. * @type {number}
  207. * @apioption plotOptions.scatter.cluster.layoutAlgorithm.iterations
  208. */
  209. /**
  210. * When `type` is set to `kmeans`,
  211. * `distance` is a maximum distance between point and cluster center
  212. * so that this point will be inside the cluster. The distance
  213. * is either a number defining pixels or a percentage
  214. * defining a percentage of the plot area width.
  215. *
  216. * @type {number|string}
  217. */
  218. distance: 40,
  219. /**
  220. * When `type` is set to `undefined` and there are more visible points
  221. * than the kmeansThreshold the `grid` algorithm is used to find
  222. * clusters, otherwise `kmeans`. It ensures good performance on
  223. * large datasets and better clusters arrangement after the zoom.
  224. */
  225. kmeansThreshold: 100
  226. },
  227. /**
  228. * Options for the cluster marker.
  229. * @extends plotOptions.series.marker
  230. * @excluding enabledThreshold, states
  231. * @type {Highcharts.PointMarkerOptionsObject}
  232. */
  233. marker: {
  234. /** @internal */
  235. symbol: 'cluster',
  236. /** @internal */
  237. radius: 15,
  238. /** @internal */
  239. lineWidth: 0,
  240. /** @internal */
  241. lineColor: '#ffffff'
  242. },
  243. /**
  244. * Fires when the cluster point is clicked and `drillToCluster` is enabled.
  245. * One parameter, `event`, is passed to the function. The default action
  246. * is to zoom to the cluster points range. This can be prevented
  247. * by calling `event.preventDefault()`.
  248. *
  249. * @type {Highcharts.MarkerClusterDrillCallbackFunction}
  250. * @product highcharts highmaps
  251. * @see [cluster.drillToCluster](#plotOptions.scatter.marker.cluster.drillToCluster)
  252. * @apioption plotOptions.scatter.cluster.events.drillToCluster
  253. */
  254. /**
  255. * An array defining zones within marker clusters.
  256. *
  257. * In styled mode, the color zones are styled with the
  258. * `.highcharts-cluster-zone-{n}` class, or custom
  259. * classed from the `className`
  260. * option.
  261. *
  262. * @sample highcharts/marker-clusters/basic
  263. * Marker clusters zones
  264. * @sample maps/marker-clusters/custom-alg
  265. * Zones on maps
  266. *
  267. * @type {Array<*>}
  268. * @product highcharts highmaps
  269. * @apioption plotOptions.scatter.cluster.zones
  270. */
  271. /**
  272. * Styled mode only. A custom class name for the zone.
  273. *
  274. * @sample highcharts/css/color-zones/
  275. * Zones styled by class name
  276. *
  277. * @type {string}
  278. * @apioption plotOptions.scatter.cluster.zones.className
  279. */
  280. /**
  281. * Settings for the cluster marker belonging to the zone.
  282. *
  283. * @see [cluster.marker](#plotOptions.scatter.cluster.marker)
  284. * @extends plotOptions.scatter.cluster.marker
  285. * @product highcharts highmaps
  286. * @apioption plotOptions.scatter.cluster.zones.marker
  287. */
  288. /**
  289. * The value where the zone starts.
  290. *
  291. * @type {number}
  292. * @product highcharts highmaps
  293. * @apioption plotOptions.scatter.cluster.zones.from
  294. */
  295. /**
  296. * The value where the zone ends.
  297. *
  298. * @type {number}
  299. * @product highcharts highmaps
  300. * @apioption plotOptions.scatter.cluster.zones.to
  301. */
  302. /**
  303. * The fill color of the cluster marker in hover state. When
  304. * `undefined`, the series' or point's fillColor for normal
  305. * state is used.
  306. *
  307. * @type {Highcharts.ColorType}
  308. * @apioption plotOptions.scatter.cluster.states.hover.fillColor
  309. */
  310. /**
  311. * Options for the cluster data labels.
  312. * @type {Highcharts.DataLabelsOptions}
  313. */
  314. dataLabels: {
  315. /** @internal */
  316. enabled: true,
  317. /** @internal */
  318. format: '{point.clusterPointsAmount}',
  319. /** @internal */
  320. verticalAlign: 'middle',
  321. /** @internal */
  322. align: 'center',
  323. /** @internal */
  324. style: {
  325. color: 'contrast'
  326. },
  327. /** @internal */
  328. inside: true
  329. }
  330. };
  331. (defaultOptions.plotOptions || {}).series = merge((defaultOptions.plotOptions || {}).series, {
  332. cluster: clusterDefaultOptions,
  333. tooltip: {
  334. /**
  335. * The HTML of the cluster point's in the tooltip. Works only with
  336. * marker-clusters module and analogously to
  337. * [pointFormat](#tooltip.pointFormat).
  338. *
  339. * The cluster tooltip can be also formatted using
  340. * `tooltip.formatter` callback function and `point.isCluster` flag.
  341. *
  342. * @sample highcharts/marker-clusters/grid
  343. * Format tooltip for cluster points.
  344. *
  345. * @sample maps/marker-clusters/europe/
  346. * Format tooltip for clusters using tooltip.formatter
  347. *
  348. * @apioption tooltip.clusterFormat
  349. */
  350. clusterFormat: '<span>Clustered points: ' +
  351. '{point.clusterPointsAmount}</span><br/>'
  352. }
  353. });
  354. // Utils.
  355. /* eslint-disable require-jsdoc */
  356. function getClusterPosition(points) {
  357. var pointsLen = points.length, sumX = 0, sumY = 0, i;
  358. for (i = 0; i < pointsLen; i++) {
  359. sumX += points[i].x;
  360. sumY += points[i].y;
  361. }
  362. return {
  363. x: sumX / pointsLen,
  364. y: sumY / pointsLen
  365. };
  366. }
  367. // Prepare array with sorted data objects to be
  368. // compared in getPointsState method.
  369. function getDataState(clusteredData, stateDataLen) {
  370. var state = [];
  371. state.length = stateDataLen;
  372. clusteredData.clusters.forEach(function (cluster) {
  373. cluster.data.forEach(function (elem) {
  374. state[elem.dataIndex] = elem;
  375. });
  376. });
  377. clusteredData.noise.forEach(function (noise) {
  378. state[noise.data[0].dataIndex] = noise.data[0];
  379. });
  380. return state;
  381. }
  382. function fadeInElement(elem, opacity, animation) {
  383. elem
  384. .attr({
  385. opacity: opacity
  386. })
  387. .animate({
  388. opacity: 1
  389. }, animation);
  390. }
  391. function fadeInStatePoint(stateObj, opacity, animation, fadeinGraphic, fadeinDataLabel) {
  392. if (stateObj.point) {
  393. if (fadeinGraphic && stateObj.point.graphic) {
  394. stateObj.point.graphic.show();
  395. fadeInElement(stateObj.point.graphic, opacity, animation);
  396. }
  397. if (fadeinDataLabel && stateObj.point.dataLabel) {
  398. stateObj.point.dataLabel.show();
  399. fadeInElement(stateObj.point.dataLabel, opacity, animation);
  400. }
  401. }
  402. }
  403. function hideStatePoint(stateObj, hideGraphic, hideDataLabel) {
  404. if (stateObj.point) {
  405. if (hideGraphic && stateObj.point.graphic) {
  406. stateObj.point.graphic.hide();
  407. }
  408. if (hideDataLabel && stateObj.point.dataLabel) {
  409. stateObj.point.dataLabel.hide();
  410. }
  411. }
  412. }
  413. function destroyOldPoints(oldState) {
  414. if (oldState) {
  415. objectEach(oldState, function (state) {
  416. if (state.point && state.point.destroy) {
  417. state.point.destroy();
  418. }
  419. });
  420. }
  421. }
  422. function fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, opacity) {
  423. // Fade in new point.
  424. fadeInStatePoint(newPointObj, opacity, animation, true, true);
  425. // Destroy old animated points.
  426. oldPoints.forEach(function (p) {
  427. if (p.point && p.point.destroy) {
  428. p.point.destroy();
  429. }
  430. });
  431. }
  432. // Generate unique stateId for a state element.
  433. function getStateId() {
  434. return Math.random().toString(36).substring(2, 7) + '-' + stateIdCounter++;
  435. }
  436. // Useful for debugging.
  437. // function drawGridLines(
  438. // series: Highcharts.Series,
  439. // options: Highcharts.MarkerClusterLayoutAlgorithmOptions
  440. // ): void {
  441. // var chart = series.chart,
  442. // xAxis = series.xAxis,
  443. // yAxis = series.yAxis,
  444. // xAxisLen = series.xAxis.len,
  445. // yAxisLen = series.yAxis.len,
  446. // i, j, elem, text,
  447. // currentX = 0,
  448. // currentY = 0,
  449. // scaledGridSize = 50,
  450. // gridX = 0,
  451. // gridY = 0,
  452. // gridOffset = series.getGridOffset(),
  453. // mapXSize, mapYSize;
  454. // if (series.debugGridLines && series.debugGridLines.length) {
  455. // series.debugGridLines.forEach(function (gridItem): void {
  456. // if (gridItem && gridItem.destroy) {
  457. // gridItem.destroy();
  458. // }
  459. // });
  460. // }
  461. // series.debugGridLines = [];
  462. // scaledGridSize = series.getScaledGridSize(options);
  463. // mapXSize = Math.abs(
  464. // xAxis.toPixels(xAxis.dataMax || 0) -
  465. // xAxis.toPixels(xAxis.dataMin || 0)
  466. // );
  467. // mapYSize = Math.abs(
  468. // yAxis.toPixels(yAxis.dataMax || 0) -
  469. // yAxis.toPixels(yAxis.dataMin || 0)
  470. // );
  471. // gridX = Math.ceil(mapXSize / scaledGridSize);
  472. // gridY = Math.ceil(mapYSize / scaledGridSize);
  473. // for (i = 0; i < gridX; i++) {
  474. // currentX = i * scaledGridSize;
  475. // if (
  476. // gridOffset.plotLeft + currentX >= 0 &&
  477. // gridOffset.plotLeft + currentX < xAxisLen
  478. // ) {
  479. // for (j = 0; j < gridY; j++) {
  480. // currentY = j * scaledGridSize;
  481. // if (
  482. // gridOffset.plotTop + currentY >= 0 &&
  483. // gridOffset.plotTop + currentY < yAxisLen
  484. // ) {
  485. // if (j % 2 === 0 && i % 2 === 0) {
  486. // var rect = chart.renderer
  487. // .rect(
  488. // gridOffset.plotLeft + currentX,
  489. // gridOffset.plotTop + currentY,
  490. // scaledGridSize * 2,
  491. // scaledGridSize * 2
  492. // )
  493. // .attr({
  494. // stroke: series.color,
  495. // 'stroke-width': '2px'
  496. // })
  497. // .add()
  498. // .toFront();
  499. // series.debugGridLines.push(rect);
  500. // }
  501. // elem = chart.renderer
  502. // .rect(
  503. // gridOffset.plotLeft + currentX,
  504. // gridOffset.plotTop + currentY,
  505. // scaledGridSize,
  506. // scaledGridSize
  507. // )
  508. // .attr({
  509. // stroke: series.color,
  510. // opacity: 0.3,
  511. // 'stroke-width': '1px'
  512. // })
  513. // .add()
  514. // .toFront();
  515. // text = chart.renderer
  516. // .text(
  517. // j + '-' + i,
  518. // gridOffset.plotLeft + currentX + 2,
  519. // gridOffset.plotTop + currentY + 7
  520. // )
  521. // .css({
  522. // fill: 'rgba(0, 0, 0, 0.7)',
  523. // fontSize: '7px'
  524. // })
  525. // .add()
  526. // .toFront();
  527. // series.debugGridLines.push(elem);
  528. // series.debugGridLines.push(text);
  529. // }
  530. // }
  531. // }
  532. // }
  533. // }
  534. /* eslint-enable require-jsdoc */
  535. // Cluster symbol.
  536. SVGRenderer.prototype.symbols.cluster = function (x, y, width, height) {
  537. var w = width / 2, h = height / 2, outerWidth = 1, space = 1, inner, outer1, outer2;
  538. inner = this.arc(x + w, y + h, w - space * 4, h - space * 4, {
  539. start: Math.PI * 0.5,
  540. end: Math.PI * 2.5,
  541. open: false
  542. });
  543. outer1 = this.arc(x + w, y + h, w - space * 3, h - space * 3, {
  544. start: Math.PI * 0.5,
  545. end: Math.PI * 2.5,
  546. innerR: w - outerWidth * 2,
  547. open: false
  548. });
  549. outer2 = this.arc(x + w, y + h, w - space, h - space, {
  550. start: Math.PI * 0.5,
  551. end: Math.PI * 2.5,
  552. innerR: w,
  553. open: false
  554. });
  555. return outer2.concat(outer1, inner);
  556. };
  557. Scatter.prototype.animateClusterPoint = function (clusterObj) {
  558. var series = this, xAxis = series.xAxis, yAxis = series.yAxis, chart = series.chart, clusterOptions = series.options.cluster, animation = animObject((clusterOptions || {}).animation), animDuration = animation.duration || 500, pointsState = (series.markerClusterInfo || {}).pointsState, newState = (pointsState || {}).newState, oldState = (pointsState || {}).oldState, parentId, oldPointObj, newPointObj, oldPoints = [], newPointBBox, offset = 0, newX = 0, newY = 0, isOldPointGrahic = false, isCbHandled = false;
  559. if (oldState && newState) {
  560. newPointObj = newState[clusterObj.stateId];
  561. newX = xAxis.toPixels(newPointObj.x) - chart.plotLeft;
  562. newY = yAxis.toPixels(newPointObj.y) - chart.plotTop;
  563. // Point has one ancestor.
  564. if (newPointObj.parentsId.length === 1) {
  565. parentId = (newState || {})[clusterObj.stateId].parentsId[0];
  566. oldPointObj = oldState[parentId];
  567. // If old and new poistions are the same do not animate.
  568. if (newPointObj.point &&
  569. newPointObj.point.graphic &&
  570. oldPointObj &&
  571. oldPointObj.point &&
  572. oldPointObj.point.plotX &&
  573. oldPointObj.point.plotY &&
  574. oldPointObj.point.plotX !== newPointObj.point.plotX &&
  575. oldPointObj.point.plotY !== newPointObj.point.plotY) {
  576. newPointBBox = newPointObj.point.graphic.getBBox();
  577. offset = newPointBBox.width / 2;
  578. newPointObj.point.graphic.attr({
  579. x: oldPointObj.point.plotX - offset,
  580. y: oldPointObj.point.plotY - offset
  581. });
  582. newPointObj.point.graphic.animate({
  583. x: newX - (newPointObj.point.graphic.radius || 0),
  584. y: newY - (newPointObj.point.graphic.radius || 0)
  585. }, animation, function () {
  586. isCbHandled = true;
  587. // Destroy old point.
  588. if (oldPointObj.point && oldPointObj.point.destroy) {
  589. oldPointObj.point.destroy();
  590. }
  591. });
  592. // Data label animation.
  593. if (newPointObj.point.dataLabel &&
  594. newPointObj.point.dataLabel.alignAttr &&
  595. oldPointObj.point.dataLabel &&
  596. oldPointObj.point.dataLabel.alignAttr) {
  597. newPointObj.point.dataLabel.attr({
  598. x: oldPointObj.point.dataLabel.alignAttr.x,
  599. y: oldPointObj.point.dataLabel.alignAttr.y
  600. });
  601. newPointObj.point.dataLabel.animate({
  602. x: newPointObj.point.dataLabel.alignAttr.x,
  603. y: newPointObj.point.dataLabel.alignAttr.y
  604. }, animation);
  605. }
  606. }
  607. }
  608. else if (newPointObj.parentsId.length === 0) {
  609. // Point has no ancestors - new point.
  610. // Hide new point.
  611. hideStatePoint(newPointObj, true, true);
  612. syncTimeout(function () {
  613. // Fade in new point.
  614. fadeInStatePoint(newPointObj, 0.1, animation, true, true);
  615. }, animDuration / 2);
  616. }
  617. else {
  618. // Point has many ancestors.
  619. // Hide new point before animation.
  620. hideStatePoint(newPointObj, true, true);
  621. newPointObj.parentsId.forEach(function (elem) {
  622. if (oldState && oldState[elem]) {
  623. oldPointObj = oldState[elem];
  624. oldPoints.push(oldPointObj);
  625. if (oldPointObj.point &&
  626. oldPointObj.point.graphic) {
  627. isOldPointGrahic = true;
  628. oldPointObj.point.graphic.show();
  629. oldPointObj.point.graphic.animate({
  630. x: newX - (oldPointObj.point.graphic.radius || 0),
  631. y: newY - (oldPointObj.point.graphic.radius || 0),
  632. opacity: 0.4
  633. }, animation, function () {
  634. isCbHandled = true;
  635. fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.7);
  636. });
  637. if (oldPointObj.point.dataLabel &&
  638. oldPointObj.point.dataLabel.y !== -9999 &&
  639. newPointObj.point &&
  640. newPointObj.point.dataLabel &&
  641. newPointObj.point.dataLabel.alignAttr) {
  642. oldPointObj.point.dataLabel.show();
  643. oldPointObj.point.dataLabel.animate({
  644. x: newPointObj.point.dataLabel.alignAttr.x,
  645. y: newPointObj.point.dataLabel.alignAttr.y,
  646. opacity: 0.4
  647. }, animation);
  648. }
  649. }
  650. }
  651. });
  652. // Make sure point is faded in.
  653. syncTimeout(function () {
  654. if (!isCbHandled) {
  655. fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.85);
  656. }
  657. }, animDuration);
  658. if (!isOldPointGrahic) {
  659. syncTimeout(function () {
  660. fadeInNewPointAndDestoryOld(newPointObj, oldPoints, animation, 0.1);
  661. }, animDuration / 2);
  662. }
  663. }
  664. }
  665. };
  666. Scatter.prototype.getGridOffset = function () {
  667. var series = this, chart = series.chart, xAxis = series.xAxis, yAxis = series.yAxis, plotLeft = 0, plotTop = 0;
  668. if (series.dataMinX && series.dataMaxX) {
  669. plotLeft = xAxis.reversed ?
  670. xAxis.toPixels(series.dataMaxX) : xAxis.toPixels(series.dataMinX);
  671. }
  672. else {
  673. plotLeft = chart.plotLeft;
  674. }
  675. if (series.dataMinY && series.dataMaxY) {
  676. plotTop = yAxis.reversed ?
  677. yAxis.toPixels(series.dataMinY) : yAxis.toPixels(series.dataMaxY);
  678. }
  679. else {
  680. plotTop = chart.plotTop;
  681. }
  682. return { plotLeft: plotLeft, plotTop: plotTop };
  683. };
  684. Scatter.prototype.getScaledGridSize = function (options) {
  685. var series = this, xAxis = series.xAxis, search = true, k = 1, divider = 1, processedGridSize = options.processedGridSize ||
  686. clusterDefaultOptions.layoutAlgorithm.gridSize, gridSize, scale, level;
  687. if (!series.gridValueSize) {
  688. series.gridValueSize = Math.abs(xAxis.toValue(processedGridSize) - xAxis.toValue(0));
  689. }
  690. gridSize = xAxis.toPixels(series.gridValueSize) - xAxis.toPixels(0);
  691. scale = +(processedGridSize / gridSize).toFixed(14);
  692. // Find the level and its divider.
  693. while (search && scale !== 1) {
  694. level = Math.pow(2, k);
  695. if (scale > 0.75 && scale < 1.25) {
  696. search = false;
  697. }
  698. else if (scale >= (1 / level) && scale < 2 * (1 / level)) {
  699. search = false;
  700. divider = level;
  701. }
  702. else if (scale <= level && scale > level / 2) {
  703. search = false;
  704. divider = 1 / level;
  705. }
  706. k++;
  707. }
  708. return (processedGridSize / divider) / scale;
  709. };
  710. Scatter.prototype.getRealExtremes = function () {
  711. var _a, _b;
  712. var series = this, chart = series.chart, xAxis = series.xAxis, yAxis = series.yAxis, realMinX = xAxis ? xAxis.toValue(chart.plotLeft) : 0, realMaxX = xAxis ?
  713. xAxis.toValue(chart.plotLeft + chart.plotWidth) : 0, realMinY = yAxis ? yAxis.toValue(chart.plotTop) : 0, realMaxY = yAxis ?
  714. yAxis.toValue(chart.plotTop + chart.plotHeight) : 0;
  715. if (realMinX > realMaxX) {
  716. _a = [realMinX, realMaxX], realMaxX = _a[0], realMinX = _a[1];
  717. }
  718. if (realMinY > realMaxY) {
  719. _b = [realMinY, realMaxY], realMaxY = _b[0], realMinY = _b[1];
  720. }
  721. return {
  722. minX: realMinX,
  723. maxX: realMaxX,
  724. minY: realMinY,
  725. maxY: realMaxY
  726. };
  727. };
  728. Scatter.prototype.onDrillToCluster = function (event) {
  729. var point = event.point || event.target;
  730. point.firePointEvent('drillToCluster', event, function (e) {
  731. var _a, _b;
  732. var point = e.point || e.target, series = point.series, xAxis = point.series.xAxis, yAxis = point.series.yAxis, chart = point.series.chart, clusterOptions = series.options.cluster, drillToCluster = (clusterOptions || {}).drillToCluster, offsetX, offsetY, sortedDataX, sortedDataY, minX, minY, maxX, maxY;
  733. if (drillToCluster && point.clusteredData) {
  734. sortedDataX = point.clusteredData.map(function (data) {
  735. return data.x;
  736. }).sort(function (a, b) { return a - b; });
  737. sortedDataY = point.clusteredData.map(function (data) {
  738. return data.y;
  739. }).sort(function (a, b) { return a - b; });
  740. minX = sortedDataX[0];
  741. maxX = sortedDataX[sortedDataX.length - 1];
  742. minY = sortedDataY[0];
  743. maxY = sortedDataY[sortedDataY.length - 1];
  744. offsetX = Math.abs((maxX - minX) * 0.1);
  745. offsetY = Math.abs((maxY - minY) * 0.1);
  746. chart.pointer.zoomX = true;
  747. chart.pointer.zoomY = true;
  748. // Swap when minus values.
  749. if (minX > maxX) {
  750. _a = [maxX, minX], minX = _a[0], maxX = _a[1];
  751. }
  752. if (minY > maxY) {
  753. _b = [maxY, minY], minY = _b[0], maxY = _b[1];
  754. }
  755. chart.zoom({
  756. originalEvent: e,
  757. xAxis: [{
  758. axis: xAxis,
  759. min: minX - offsetX,
  760. max: maxX + offsetX
  761. }],
  762. yAxis: [{
  763. axis: yAxis,
  764. min: minY - offsetY,
  765. max: maxY + offsetY
  766. }]
  767. });
  768. }
  769. });
  770. };
  771. Scatter.prototype.getClusterDistancesFromPoint = function (clusters, pointX, pointY) {
  772. var series = this, xAxis = series.xAxis, yAxis = series.yAxis, pointClusterDistance = [], j, distance;
  773. for (j = 0; j < clusters.length; j++) {
  774. distance = Math.sqrt(Math.pow(xAxis.toPixels(pointX) -
  775. xAxis.toPixels(clusters[j].posX), 2) +
  776. Math.pow(yAxis.toPixels(pointY) -
  777. yAxis.toPixels(clusters[j].posY), 2));
  778. pointClusterDistance.push({
  779. clusterIndex: j,
  780. distance: distance
  781. });
  782. }
  783. return pointClusterDistance.sort(function (a, b) { return a.distance - b.distance; });
  784. };
  785. // Point state used when animation is enabled to compare
  786. // and bind old points with new ones.
  787. Scatter.prototype.getPointsState = function (clusteredData, oldMarkerClusterInfo, dataLength) {
  788. var oldDataStateArr = oldMarkerClusterInfo ?
  789. getDataState(oldMarkerClusterInfo, dataLength) : [], newDataStateArr = getDataState(clusteredData, dataLength), state = {}, newState, oldState, i;
  790. // Clear global array before populate with new ids.
  791. oldPointsStateId = [];
  792. // Build points state structure.
  793. clusteredData.clusters.forEach(function (cluster) {
  794. state[cluster.stateId] = {
  795. x: cluster.x,
  796. y: cluster.y,
  797. id: cluster.stateId,
  798. point: cluster.point,
  799. parentsId: []
  800. };
  801. });
  802. clusteredData.noise.forEach(function (noise) {
  803. state[noise.stateId] = {
  804. x: noise.x,
  805. y: noise.y,
  806. id: noise.stateId,
  807. point: noise.point,
  808. parentsId: []
  809. };
  810. });
  811. // Bind new and old state.
  812. for (i = 0; i < newDataStateArr.length; i++) {
  813. newState = newDataStateArr[i];
  814. oldState = oldDataStateArr[i];
  815. if (newState &&
  816. oldState &&
  817. newState.parentStateId &&
  818. oldState.parentStateId &&
  819. state[newState.parentStateId] &&
  820. state[newState.parentStateId].parentsId.indexOf(oldState.parentStateId) === -1) {
  821. state[newState.parentStateId].parentsId.push(oldState.parentStateId);
  822. if (oldPointsStateId.indexOf(oldState.parentStateId) === -1) {
  823. oldPointsStateId.push(oldState.parentStateId);
  824. }
  825. }
  826. }
  827. return state;
  828. };
  829. Scatter.prototype.markerClusterAlgorithms = {
  830. grid: function (dataX, dataY, dataIndexes, options) {
  831. var series = this, xAxis = series.xAxis, yAxis = series.yAxis, grid = {}, gridOffset = series.getGridOffset(), scaledGridSize, x, y, gridX, gridY, key, i;
  832. // drawGridLines(series, options);
  833. scaledGridSize = series.getScaledGridSize(options);
  834. for (i = 0; i < dataX.length; i++) {
  835. x = xAxis.toPixels(dataX[i]) - gridOffset.plotLeft;
  836. y = yAxis.toPixels(dataY[i]) - gridOffset.plotTop;
  837. gridX = Math.floor(x / scaledGridSize);
  838. gridY = Math.floor(y / scaledGridSize);
  839. key = gridY + '-' + gridX;
  840. if (!grid[key]) {
  841. grid[key] = [];
  842. }
  843. grid[key].push({
  844. dataIndex: dataIndexes[i],
  845. x: dataX[i],
  846. y: dataY[i]
  847. });
  848. }
  849. return grid;
  850. },
  851. kmeans: function (dataX, dataY, dataIndexes, options) {
  852. var series = this, clusters = [], noise = [], group = {}, pointMaxDistance = options.processedDistance ||
  853. clusterDefaultOptions.layoutAlgorithm.distance, iterations = options.iterations,
  854. // Max pixel difference beetwen new and old cluster position.
  855. maxClusterShift = 1, currentIteration = 0, repeat = true, pointX = 0, pointY = 0, tempPos, pointClusterDistance = [], groupedData, key, i, j;
  856. options.processedGridSize = options.processedDistance;
  857. // Use grid method to get groupedData object.
  858. groupedData = series.markerClusterAlgorithms ?
  859. series.markerClusterAlgorithms.grid.call(series, dataX, dataY, dataIndexes, options) : {};
  860. // Find clusters amount and its start positions
  861. // based on grid grouped data.
  862. for (key in groupedData) {
  863. if (groupedData[key].length > 1) {
  864. tempPos = getClusterPosition(groupedData[key]);
  865. clusters.push({
  866. posX: tempPos.x,
  867. posY: tempPos.y,
  868. oldX: 0,
  869. oldY: 0,
  870. startPointsLen: groupedData[key].length,
  871. points: []
  872. });
  873. }
  874. }
  875. // Start kmeans iteration process.
  876. while (repeat) {
  877. clusters.map(function (c) {
  878. c.points.length = 0;
  879. return c;
  880. });
  881. noise.length = 0;
  882. for (i = 0; i < dataX.length; i++) {
  883. pointX = dataX[i];
  884. pointY = dataY[i];
  885. pointClusterDistance = series.getClusterDistancesFromPoint(clusters, pointX, pointY);
  886. if (pointClusterDistance.length &&
  887. pointClusterDistance[0].distance < pointMaxDistance) {
  888. clusters[pointClusterDistance[0].clusterIndex].points.push({
  889. x: pointX,
  890. y: pointY,
  891. dataIndex: dataIndexes[i]
  892. });
  893. }
  894. else {
  895. noise.push({
  896. x: pointX,
  897. y: pointY,
  898. dataIndex: dataIndexes[i]
  899. });
  900. }
  901. }
  902. // When cluster points array has only one point the
  903. // point should be classified again.
  904. for (j = 0; j < clusters.length; j++) {
  905. if (clusters[j].points.length === 1) {
  906. pointClusterDistance = series.getClusterDistancesFromPoint(clusters, clusters[j].points[0].x, clusters[j].points[0].y);
  907. if (pointClusterDistance[1].distance < pointMaxDistance) {
  908. // Add point to the next closest cluster.
  909. clusters[pointClusterDistance[1].clusterIndex].points
  910. .push(clusters[j].points[0]);
  911. // Clear points array.
  912. clusters[pointClusterDistance[0].clusterIndex]
  913. .points.length = 0;
  914. }
  915. }
  916. }
  917. // Compute a new clusters position and check if it
  918. // is different than the old one.
  919. repeat = false;
  920. for (j = 0; j < clusters.length; j++) {
  921. tempPos = getClusterPosition(clusters[j].points);
  922. clusters[j].oldX = clusters[j].posX;
  923. clusters[j].oldY = clusters[j].posY;
  924. clusters[j].posX = tempPos.x;
  925. clusters[j].posY = tempPos.y;
  926. // Repeat the algorithm if at least one cluster
  927. // is shifted more than maxClusterShift property.
  928. if (clusters[j].posX > clusters[j].oldX + maxClusterShift ||
  929. clusters[j].posX < clusters[j].oldX - maxClusterShift ||
  930. clusters[j].posY > clusters[j].oldY + maxClusterShift ||
  931. clusters[j].posY < clusters[j].oldY - maxClusterShift) {
  932. repeat = true;
  933. }
  934. }
  935. // If iterations property is set repeat the algorithm
  936. // specified amount of times.
  937. if (iterations) {
  938. repeat = currentIteration < iterations - 1;
  939. }
  940. currentIteration++;
  941. }
  942. clusters.forEach(function (cluster, i) {
  943. group['cluster' + i] = cluster.points;
  944. });
  945. noise.forEach(function (noise, i) {
  946. group['noise' + i] = [noise];
  947. });
  948. return group;
  949. },
  950. optimizedKmeans: function (processedXData, processedYData, dataIndexes, options) {
  951. var series = this, xAxis = series.xAxis, yAxis = series.yAxis, pointMaxDistance = options.processedDistance ||
  952. clusterDefaultOptions.layoutAlgorithm.gridSize, group = {}, extremes = series.getRealExtremes(), clusterMarkerOptions = (series.options.cluster || {}).marker, offset, distance, radius;
  953. if (!series.markerClusterInfo || (series.initMaxX && series.initMaxX < extremes.maxX ||
  954. series.initMinX && series.initMinX > extremes.minX ||
  955. series.initMaxY && series.initMaxY < extremes.maxY ||
  956. series.initMinY && series.initMinY > extremes.minY)) {
  957. series.initMaxX = extremes.maxX;
  958. series.initMinX = extremes.minX;
  959. series.initMaxY = extremes.maxY;
  960. series.initMinY = extremes.minY;
  961. group = series.markerClusterAlgorithms ?
  962. series.markerClusterAlgorithms.kmeans.call(series, processedXData, processedYData, dataIndexes, options) : {};
  963. series.baseClusters = null;
  964. }
  965. else {
  966. if (!series.baseClusters) {
  967. series.baseClusters = {
  968. clusters: series.markerClusterInfo.clusters,
  969. noise: series.markerClusterInfo.noise
  970. };
  971. }
  972. series.baseClusters.clusters.forEach(function (cluster) {
  973. cluster.pointsOutside = [];
  974. cluster.pointsInside = [];
  975. cluster.data.forEach(function (dataPoint) {
  976. distance = Math.sqrt(Math.pow(xAxis.toPixels(dataPoint.x) -
  977. xAxis.toPixels(cluster.x), 2) +
  978. Math.pow(yAxis.toPixels(dataPoint.y) -
  979. yAxis.toPixels(cluster.y), 2));
  980. if (cluster.clusterZone &&
  981. cluster.clusterZone.marker &&
  982. cluster.clusterZone.marker.radius) {
  983. radius = cluster.clusterZone.marker.radius;
  984. }
  985. else if (clusterMarkerOptions &&
  986. clusterMarkerOptions.radius) {
  987. radius = clusterMarkerOptions.radius;
  988. }
  989. else {
  990. radius = clusterDefaultOptions.marker.radius;
  991. }
  992. offset = pointMaxDistance - radius >= 0 ?
  993. pointMaxDistance - radius : radius;
  994. if (distance > radius + offset &&
  995. defined(cluster.pointsOutside)) {
  996. cluster.pointsOutside.push(dataPoint);
  997. }
  998. else if (defined(cluster.pointsInside)) {
  999. cluster.pointsInside.push(dataPoint);
  1000. }
  1001. });
  1002. if (cluster.pointsInside.length) {
  1003. group[cluster.id] = cluster.pointsInside;
  1004. }
  1005. cluster.pointsOutside.forEach(function (p, i) {
  1006. group[cluster.id + '_noise' + i] = [p];
  1007. });
  1008. });
  1009. series.baseClusters.noise.forEach(function (noise) {
  1010. group[noise.id] = noise.data;
  1011. });
  1012. }
  1013. return group;
  1014. }
  1015. };
  1016. Scatter.prototype.preventClusterCollisions = function (props) {
  1017. var series = this, xAxis = series.xAxis, yAxis = series.yAxis, _a = props.key.split('-').map(parseFloat), gridY = _a[0], gridX = _a[1], gridSize = props.gridSize, groupedData = props.groupedData, defaultRadius = props.defaultRadius, clusterRadius = props.clusterRadius, gridXPx = gridX * gridSize, gridYPx = gridY * gridSize, xPixel = xAxis.toPixels(props.x), yPixel = yAxis.toPixels(props.y), gridsToCheckCollision = [], pointsLen = 0, radius = 0, clusterMarkerOptions = (series.options.cluster || {}).marker, zoneOptions = (series.options.cluster || {}).zones, gridOffset = series.getGridOffset(), nextXPixel, nextYPixel, signX, signY, cornerGridX, cornerGridY, i, j, itemX, itemY, nextClusterPos, maxDist, keys, x, y;
  1018. // Distance to the grid start.
  1019. xPixel -= gridOffset.plotLeft;
  1020. yPixel -= gridOffset.plotTop;
  1021. for (i = 1; i < 5; i++) {
  1022. signX = i % 2 ? -1 : 1;
  1023. signY = i < 3 ? -1 : 1;
  1024. cornerGridX = Math.floor((xPixel + signX * clusterRadius) / gridSize);
  1025. cornerGridY = Math.floor((yPixel + signY * clusterRadius) / gridSize);
  1026. keys = [
  1027. cornerGridY + '-' + cornerGridX,
  1028. cornerGridY + '-' + gridX,
  1029. gridY + '-' + cornerGridX
  1030. ];
  1031. for (j = 0; j < keys.length; j++) {
  1032. if (gridsToCheckCollision.indexOf(keys[j]) === -1 &&
  1033. keys[j] !== props.key) {
  1034. gridsToCheckCollision.push(keys[j]);
  1035. }
  1036. }
  1037. }
  1038. gridsToCheckCollision.forEach(function (item) {
  1039. var _a;
  1040. if (groupedData[item]) {
  1041. // Cluster or noise position is already computed.
  1042. if (!groupedData[item].posX) {
  1043. nextClusterPos = getClusterPosition(groupedData[item]);
  1044. groupedData[item].posX = nextClusterPos.x;
  1045. groupedData[item].posY = nextClusterPos.y;
  1046. }
  1047. nextXPixel = xAxis.toPixels(groupedData[item].posX || 0) -
  1048. gridOffset.plotLeft;
  1049. nextYPixel = yAxis.toPixels(groupedData[item].posY || 0) -
  1050. gridOffset.plotTop;
  1051. _a = item.split('-').map(parseFloat), itemY = _a[0], itemX = _a[1];
  1052. if (zoneOptions) {
  1053. pointsLen = groupedData[item].length;
  1054. for (i = 0; i < zoneOptions.length; i++) {
  1055. if (pointsLen >= zoneOptions[i].from &&
  1056. pointsLen <= zoneOptions[i].to) {
  1057. if (defined((zoneOptions[i].marker || {}).radius)) {
  1058. radius = zoneOptions[i].marker.radius || 0;
  1059. }
  1060. else if (clusterMarkerOptions &&
  1061. clusterMarkerOptions.radius) {
  1062. radius = clusterMarkerOptions.radius;
  1063. }
  1064. else {
  1065. radius = clusterDefaultOptions.marker.radius;
  1066. }
  1067. }
  1068. }
  1069. }
  1070. if (groupedData[item].length > 1 &&
  1071. radius === 0 &&
  1072. clusterMarkerOptions &&
  1073. clusterMarkerOptions.radius) {
  1074. radius = clusterMarkerOptions.radius;
  1075. }
  1076. else if (groupedData[item].length === 1) {
  1077. radius = defaultRadius;
  1078. }
  1079. maxDist = clusterRadius + radius;
  1080. radius = 0;
  1081. if (itemX !== gridX &&
  1082. Math.abs(xPixel - nextXPixel) < maxDist) {
  1083. xPixel = itemX - gridX < 0 ? gridXPx + clusterRadius :
  1084. gridXPx + gridSize - clusterRadius;
  1085. }
  1086. if (itemY !== gridY &&
  1087. Math.abs(yPixel - nextYPixel) < maxDist) {
  1088. yPixel = itemY - gridY < 0 ? gridYPx + clusterRadius :
  1089. gridYPx + gridSize - clusterRadius;
  1090. }
  1091. }
  1092. });
  1093. x = xAxis.toValue(xPixel + gridOffset.plotLeft);
  1094. y = yAxis.toValue(yPixel + gridOffset.plotTop);
  1095. groupedData[props.key].posX = x;
  1096. groupedData[props.key].posY = y;
  1097. return { x: x, y: y };
  1098. };
  1099. // Check if user algorithm result is valid groupedDataObject.
  1100. Scatter.prototype.isValidGroupedDataObject = function (groupedData) {
  1101. var result = false, i;
  1102. if (!isObject(groupedData)) {
  1103. return false;
  1104. }
  1105. objectEach(groupedData, function (elem) {
  1106. result = true;
  1107. if (!isArray(elem) || !elem.length) {
  1108. result = false;
  1109. return;
  1110. }
  1111. for (i = 0; i < elem.length; i++) {
  1112. if (!isObject(elem[i]) || (!elem[i].x || !elem[i].y)) {
  1113. result = false;
  1114. return;
  1115. }
  1116. }
  1117. });
  1118. return result;
  1119. };
  1120. Scatter.prototype.getClusteredData = function (groupedData, options) {
  1121. var series = this, groupedXData = [], groupedYData = [], clusters = [], // Container for clusters.
  1122. noise = [], // Container for points not belonging to any cluster.
  1123. groupMap = [], index = 0,
  1124. // Prevent minimumClusterSize lower than 2.
  1125. minimumClusterSize = Math.max(2, options.minimumClusterSize || 2), stateId, point, points, pointUserOptions, pointsLen, marker, clusterPos, pointOptions, clusterTempPos, zoneOptions, clusterZone, clusterZoneClassName, i, k;
  1126. // Check if groupedData is valid when user uses a custom algorithm.
  1127. if (isFunction(options.layoutAlgorithm.type) &&
  1128. !series.isValidGroupedDataObject(groupedData)) {
  1129. error('Highcharts marker-clusters module: ' +
  1130. 'The custom algorithm result is not valid!', false, series.chart);
  1131. return false;
  1132. }
  1133. for (k in groupedData) {
  1134. if (groupedData[k].length >= minimumClusterSize) {
  1135. points = groupedData[k];
  1136. stateId = getStateId();
  1137. pointsLen = points.length;
  1138. // Get zone options for cluster.
  1139. if (options.zones) {
  1140. for (i = 0; i < options.zones.length; i++) {
  1141. if (pointsLen >= options.zones[i].from &&
  1142. pointsLen <= options.zones[i].to) {
  1143. clusterZone = options.zones[i];
  1144. clusterZone.zoneIndex = i;
  1145. zoneOptions = options.zones[i].marker;
  1146. clusterZoneClassName = options.zones[i].className;
  1147. }
  1148. }
  1149. }
  1150. clusterTempPos = getClusterPosition(points);
  1151. if (options.layoutAlgorithm.type === 'grid' &&
  1152. !options.allowOverlap) {
  1153. marker = series.options.marker || {};
  1154. clusterPos = series.preventClusterCollisions({
  1155. x: clusterTempPos.x,
  1156. y: clusterTempPos.y,
  1157. key: k,
  1158. groupedData: groupedData,
  1159. gridSize: series.getScaledGridSize(options.layoutAlgorithm),
  1160. defaultRadius: marker.radius || 3 + (marker.lineWidth || 0),
  1161. clusterRadius: (zoneOptions && zoneOptions.radius) ?
  1162. zoneOptions.radius :
  1163. (options.marker || {}).radius ||
  1164. clusterDefaultOptions.marker.radius
  1165. });
  1166. }
  1167. else {
  1168. clusterPos = {
  1169. x: clusterTempPos.x,
  1170. y: clusterTempPos.y
  1171. };
  1172. }
  1173. for (i = 0; i < pointsLen; i++) {
  1174. points[i].parentStateId = stateId;
  1175. }
  1176. clusters.push({
  1177. x: clusterPos.x,
  1178. y: clusterPos.y,
  1179. id: k,
  1180. stateId: stateId,
  1181. index: index,
  1182. data: points,
  1183. clusterZone: clusterZone,
  1184. clusterZoneClassName: clusterZoneClassName
  1185. });
  1186. groupedXData.push(clusterPos.x);
  1187. groupedYData.push(clusterPos.y);
  1188. groupMap.push({
  1189. options: {
  1190. formatPrefix: 'cluster',
  1191. dataLabels: options.dataLabels,
  1192. marker: merge(options.marker, {
  1193. states: options.states
  1194. }, zoneOptions || {})
  1195. }
  1196. });
  1197. // Save cluster data points options.
  1198. if (series.options.data && series.options.data.length) {
  1199. for (i = 0; i < pointsLen; i++) {
  1200. if (isObject(series.options.data[points[i].dataIndex])) {
  1201. points[i].options =
  1202. series.options.data[points[i].dataIndex];
  1203. }
  1204. }
  1205. }
  1206. index++;
  1207. zoneOptions = null;
  1208. }
  1209. else {
  1210. for (i = 0; i < groupedData[k].length; i++) {
  1211. // Points not belonging to any cluster.
  1212. point = groupedData[k][i];
  1213. stateId = getStateId();
  1214. pointOptions = null;
  1215. pointUserOptions =
  1216. ((series.options || {}).data || [])[point.dataIndex];
  1217. groupedXData.push(point.x);
  1218. groupedYData.push(point.y);
  1219. point.parentStateId = stateId;
  1220. noise.push({
  1221. x: point.x,
  1222. y: point.y,
  1223. id: k,
  1224. stateId: stateId,
  1225. index: index,
  1226. data: groupedData[k]
  1227. });
  1228. if (pointUserOptions &&
  1229. typeof pointUserOptions === 'object' &&
  1230. !isArray(pointUserOptions)) {
  1231. pointOptions = merge(pointUserOptions, { x: point.x, y: point.y });
  1232. }
  1233. else {
  1234. pointOptions = {
  1235. userOptions: pointUserOptions,
  1236. x: point.x,
  1237. y: point.y
  1238. };
  1239. }
  1240. groupMap.push({ options: pointOptions });
  1241. index++;
  1242. }
  1243. }
  1244. }
  1245. return {
  1246. clusters: clusters,
  1247. noise: noise,
  1248. groupedXData: groupedXData,
  1249. groupedYData: groupedYData,
  1250. groupMap: groupMap
  1251. };
  1252. };
  1253. // Destroy clustered data points.
  1254. Scatter.prototype.destroyClusteredData = function () {
  1255. var clusteredSeriesData = this.markerClusterSeriesData;
  1256. // Clear previous groups.
  1257. (clusteredSeriesData || []).forEach(function (point) {
  1258. if (point && point.destroy) {
  1259. point.destroy();
  1260. }
  1261. });
  1262. this.markerClusterSeriesData = null;
  1263. };
  1264. // Hide clustered data points.
  1265. Scatter.prototype.hideClusteredData = function () {
  1266. var series = this, clusteredSeriesData = this.markerClusterSeriesData, oldState = ((series.markerClusterInfo || {}).pointsState || {}).oldState || {}, oldPointsId = oldPointsStateId.map(function (elem) {
  1267. return (oldState[elem].point || {}).id || '';
  1268. });
  1269. (clusteredSeriesData || []).forEach(function (point) {
  1270. // If an old point is used in animation hide it, otherwise destroy.
  1271. if (point &&
  1272. oldPointsId.indexOf(point.id) !== -1) {
  1273. if (point.graphic) {
  1274. point.graphic.hide();
  1275. }
  1276. if (point.dataLabel) {
  1277. point.dataLabel.hide();
  1278. }
  1279. }
  1280. else {
  1281. if (point && point.destroy) {
  1282. point.destroy();
  1283. }
  1284. }
  1285. });
  1286. };
  1287. // Override the generatePoints method by adding a reference to grouped data.
  1288. Scatter.prototype.generatePoints = function () {
  1289. var series = this, chart = series.chart, xAxis = series.xAxis, yAxis = series.yAxis, clusterOptions = series.options.cluster, realExtremes = series.getRealExtremes(), visibleXData = [], visibleYData = [], visibleDataIndexes = [], oldPointsState, oldDataLen, oldMarkerClusterInfo, kmeansThreshold, cropDataOffsetX, cropDataOffsetY, seriesMinX, seriesMaxX, seriesMinY, seriesMaxY, type, algorithm, clusteredData, groupedData, layoutAlgOptions, point, i;
  1290. if (clusterOptions &&
  1291. clusterOptions.enabled &&
  1292. series.xData &&
  1293. series.yData &&
  1294. !chart.polar) {
  1295. type = clusterOptions.layoutAlgorithm.type;
  1296. layoutAlgOptions = clusterOptions.layoutAlgorithm;
  1297. // Get processed algorithm properties.
  1298. layoutAlgOptions.processedGridSize = relativeLength(layoutAlgOptions.gridSize ||
  1299. clusterDefaultOptions.layoutAlgorithm.gridSize, chart.plotWidth);
  1300. layoutAlgOptions.processedDistance = relativeLength(layoutAlgOptions.distance ||
  1301. clusterDefaultOptions.layoutAlgorithm.distance, chart.plotWidth);
  1302. kmeansThreshold = layoutAlgOptions.kmeansThreshold ||
  1303. clusterDefaultOptions.layoutAlgorithm.kmeansThreshold;
  1304. // Offset to prevent cluster size changes.
  1305. cropDataOffsetX = Math.abs(xAxis.toValue(layoutAlgOptions.processedGridSize / 2) -
  1306. xAxis.toValue(0));
  1307. cropDataOffsetY = Math.abs(yAxis.toValue(layoutAlgOptions.processedGridSize / 2) -
  1308. yAxis.toValue(0));
  1309. // Get only visible data.
  1310. for (i = 0; i < series.xData.length; i++) {
  1311. if (!series.dataMaxX) {
  1312. if (!defined(seriesMaxX) ||
  1313. !defined(seriesMinX) ||
  1314. !defined(seriesMaxY) ||
  1315. !defined(seriesMinY)) {
  1316. seriesMaxX = seriesMinX = series.xData[i];
  1317. seriesMaxY = seriesMinY = series.yData[i];
  1318. }
  1319. else if (isNumber(series.yData[i]) &&
  1320. isNumber(seriesMaxY) &&
  1321. isNumber(seriesMinY)) {
  1322. seriesMaxX = Math.max(series.xData[i], seriesMaxX);
  1323. seriesMinX = Math.min(series.xData[i], seriesMinX);
  1324. seriesMaxY = Math.max(series.yData[i] || seriesMaxY, seriesMaxY);
  1325. seriesMinY = Math.min(series.yData[i] || seriesMinY, seriesMinY);
  1326. }
  1327. }
  1328. // Crop data to visible ones with appropriate offset to prevent
  1329. // cluster size changes on the edge of the plot area.
  1330. if (series.xData[i] >= (realExtremes.minX - cropDataOffsetX) &&
  1331. series.xData[i] <= (realExtremes.maxX + cropDataOffsetX) &&
  1332. (series.yData[i] || realExtremes.minY) >=
  1333. (realExtremes.minY - cropDataOffsetY) &&
  1334. (series.yData[i] || realExtremes.maxY) <=
  1335. (realExtremes.maxY + cropDataOffsetY)) {
  1336. visibleXData.push(series.xData[i]);
  1337. visibleYData.push(series.yData[i]);
  1338. visibleDataIndexes.push(i);
  1339. }
  1340. }
  1341. // Save data max values.
  1342. if (defined(seriesMaxX) && defined(seriesMinX) &&
  1343. isNumber(seriesMaxY) && isNumber(seriesMinY)) {
  1344. series.dataMaxX = seriesMaxX;
  1345. series.dataMinX = seriesMinX;
  1346. series.dataMaxY = seriesMaxY;
  1347. series.dataMinY = seriesMinY;
  1348. }
  1349. if (isFunction(type)) {
  1350. algorithm = type;
  1351. }
  1352. else if (series.markerClusterAlgorithms) {
  1353. if (type && series.markerClusterAlgorithms[type]) {
  1354. algorithm = series.markerClusterAlgorithms[type];
  1355. }
  1356. else {
  1357. algorithm = visibleXData.length < kmeansThreshold ?
  1358. series.markerClusterAlgorithms.kmeans :
  1359. series.markerClusterAlgorithms.grid;
  1360. }
  1361. }
  1362. else {
  1363. algorithm = function () {
  1364. return false;
  1365. };
  1366. }
  1367. groupedData = algorithm.call(this, visibleXData, visibleYData, visibleDataIndexes, layoutAlgOptions);
  1368. clusteredData = groupedData ? series.getClusteredData(groupedData, clusterOptions) : groupedData;
  1369. // When animation is enabled get old points state.
  1370. if (clusterOptions.animation &&
  1371. series.markerClusterInfo &&
  1372. series.markerClusterInfo.pointsState &&
  1373. series.markerClusterInfo.pointsState.oldState) {
  1374. // Destroy old points.
  1375. destroyOldPoints(series.markerClusterInfo.pointsState.oldState);
  1376. oldPointsState = series.markerClusterInfo.pointsState.newState;
  1377. }
  1378. else {
  1379. oldPointsState = {};
  1380. }
  1381. // Save points old state info.
  1382. oldDataLen = series.xData.length;
  1383. oldMarkerClusterInfo = series.markerClusterInfo;
  1384. if (clusteredData) {
  1385. series.processedXData = clusteredData.groupedXData;
  1386. series.processedYData = clusteredData.groupedYData;
  1387. series.hasGroupedData = true;
  1388. series.markerClusterInfo = clusteredData;
  1389. series.groupMap = clusteredData.groupMap;
  1390. }
  1391. baseGeneratePoints.apply(this);
  1392. if (clusteredData && series.markerClusterInfo) {
  1393. // Mark cluster points. Safe point reference in the cluster object.
  1394. (series.markerClusterInfo.clusters || []).forEach(function (cluster) {
  1395. point = series.points[cluster.index];
  1396. point.isCluster = true;
  1397. point.clusteredData = cluster.data;
  1398. point.clusterPointsAmount = cluster.data.length;
  1399. cluster.point = point;
  1400. // Add zoom to cluster range.
  1401. addEvent(point, 'click', series.onDrillToCluster);
  1402. });
  1403. // Safe point reference in the noise object.
  1404. (series.markerClusterInfo.noise || []).forEach(function (noise) {
  1405. noise.point = series.points[noise.index];
  1406. });
  1407. // When animation is enabled save points state.
  1408. if (clusterOptions.animation &&
  1409. series.markerClusterInfo) {
  1410. series.markerClusterInfo.pointsState = {
  1411. oldState: oldPointsState,
  1412. newState: series.getPointsState(clusteredData, oldMarkerClusterInfo, oldDataLen)
  1413. };
  1414. }
  1415. // Record grouped data in order to let it be destroyed the next time
  1416. // processData runs.
  1417. if (!clusterOptions.animation) {
  1418. this.destroyClusteredData();
  1419. }
  1420. else {
  1421. this.hideClusteredData();
  1422. }
  1423. this.markerClusterSeriesData =
  1424. this.hasGroupedData ? this.points : null;
  1425. }
  1426. }
  1427. else {
  1428. baseGeneratePoints.apply(this);
  1429. }
  1430. };
  1431. // Handle animation.
  1432. addEvent(Chart, 'render', function () {
  1433. var chart = this;
  1434. (chart.series || []).forEach(function (series) {
  1435. if (series.markerClusterInfo) {
  1436. var options = series.options.cluster, pointsState = (series.markerClusterInfo || {}).pointsState, oldState = (pointsState || {}).oldState;
  1437. if ((options || {}).animation &&
  1438. series.markerClusterInfo &&
  1439. series.chart.pointer.pinchDown.length === 0 &&
  1440. (series.xAxis.eventArgs || {}).trigger !== 'pan' &&
  1441. oldState &&
  1442. Object.keys(oldState).length) {
  1443. series.markerClusterInfo.clusters.forEach(function (cluster) {
  1444. series.animateClusterPoint(cluster);
  1445. });
  1446. series.markerClusterInfo.noise.forEach(function (noise) {
  1447. series.animateClusterPoint(noise);
  1448. });
  1449. }
  1450. }
  1451. });
  1452. });
  1453. // Override point prototype to throw a warning when trying to update
  1454. // clustered point.
  1455. addEvent(Point, 'update', function () {
  1456. if (this.dataGroup) {
  1457. error('Highcharts marker-clusters module: ' +
  1458. 'Running `Point.update` when point belongs to clustered series' +
  1459. ' is not supported.', false, this.series.chart);
  1460. return false;
  1461. }
  1462. });
  1463. // Destroy grouped data on series destroy.
  1464. addEvent(Series, 'destroy', Scatter.prototype.destroyClusteredData);
  1465. // Add classes, change mouse cursor.
  1466. addEvent(Series, 'afterRender', function () {
  1467. var series = this, clusterZoomEnabled = (series.options.cluster || {}).drillToCluster;
  1468. if (series.markerClusterInfo && series.markerClusterInfo.clusters) {
  1469. series.markerClusterInfo.clusters.forEach(function (cluster) {
  1470. if (cluster.point && cluster.point.graphic) {
  1471. cluster.point.graphic.addClass('highcharts-cluster-point');
  1472. // Change cursor to pointer when drillToCluster is enabled.
  1473. if (clusterZoomEnabled && cluster.point) {
  1474. cluster.point.graphic.css({
  1475. cursor: 'pointer'
  1476. });
  1477. if (cluster.point.dataLabel) {
  1478. cluster.point.dataLabel.css({
  1479. cursor: 'pointer'
  1480. });
  1481. }
  1482. }
  1483. if (defined(cluster.clusterZone)) {
  1484. cluster.point.graphic.addClass(cluster.clusterZoneClassName ||
  1485. 'highcharts-cluster-zone-' +
  1486. cluster.clusterZone.zoneIndex);
  1487. }
  1488. }
  1489. });
  1490. }
  1491. });
  1492. addEvent(Point, 'drillToCluster', function (event) {
  1493. var point = event.point || event.target, series = point.series, clusterOptions = series.options.cluster, onDrillToCluster = ((clusterOptions || {}).events || {}).drillToCluster;
  1494. if (isFunction(onDrillToCluster)) {
  1495. onDrillToCluster.call(this, event);
  1496. }
  1497. });
  1498. // Destroy the old tooltip after zoom.
  1499. addEvent(Axis, 'setExtremes', function () {
  1500. var chart = this.chart, animationDuration = 0, animation;
  1501. chart.series.forEach(function (series) {
  1502. if (series.markerClusterInfo) {
  1503. animation = animObject((series.options.cluster || {}).animation);
  1504. animationDuration = animation.duration || 0;
  1505. }
  1506. });
  1507. syncTimeout(function () {
  1508. if (chart.tooltip) {
  1509. chart.tooltip.destroy();
  1510. }
  1511. }, animationDuration);
  1512. });