MarkerClusters.js 63 KB

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