marker-clusters.src.js 80 KB

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