bm.markercluster-src.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.BM = global.BM || {}, global.BM.markercluster = global.BM.markercluster || {})));
  5. }(this, (function (exports) {
  6. 'use strict';
  7. var MarkerClusterGroup = BM.MarkerClusterGroup = BM.FeatureGroup.extend({
  8. options: {
  9. maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center
  10. iconCreateFunction: null,
  11. clusterPane: BM.Marker.prototype.options.pane,
  12. spiderfyOnMaxZoom: true,
  13. showCoverageOnHover: true,
  14. zoomToBoundsOnClick: true,
  15. singleMarkerMode: false,
  16. disableClusteringAtZoom: null,
  17. // Setting this to false prevents the removal of any clusters outside of the viewpoint, which
  18. // is the default behaviour for performance reasons.
  19. removeOutsideVisibleBounds: true,
  20. // Set to false to disable all animations (zoom and spiderfy).
  21. // If false, option animateAddingMarkers below has no effect.
  22. // If BM.DomUtil.TRANSITION is falsy, this option has no effect.
  23. animate: true,
  24. //Whether to animate adding markers after adding the MarkerClusterGroup to the map
  25. // If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains.
  26. animateAddingMarkers: false,
  27. //Increase to increase the distance away that spiderfied markers appear from the center
  28. spiderfyDistanceMultiplier: 1,
  29. // Make it possible to specify a polyline options on a spider leg
  30. spiderLegPolylineOptions: {
  31. weight: 1.5,
  32. color: '#222',
  33. opacity: 0.5
  34. },
  35. // When bulk adding layers, adds markers in chunks. Means addLayers may not add all the layers in the call, others will be loaded during setTimeouts
  36. chunkedLoading: false,
  37. chunkInterval: 200, // process markers for a maximum of ~ n milliseconds (then trigger the chunkProgress callback)
  38. chunkDelay: 50, // at the end of each interval, give n milliseconds back to system/browser
  39. chunkProgress: null, // progress callback: function(processed, total, elapsed) (e.g. for a progress indicator)
  40. //Options to pass to the BM.Polygon constructor
  41. polygonOptions: {}
  42. },
  43. initialize: function (options) {
  44. BM.Util.setOptions(this, options);
  45. if (!this.options.iconCreateFunction) {
  46. this.options.iconCreateFunction = this._defaultIconCreateFunction;
  47. }
  48. this._featureGroup = BM.featureGroup();
  49. this._featureGroup.addEventParent(this);
  50. this._nonPointGroup = BM.featureGroup();
  51. this._nonPointGroup.addEventParent(this);
  52. this._inZoomAnimation = 0;
  53. this._needsClustering = [];
  54. this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of
  55. //The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
  56. this._currentShownBounds = null;
  57. this._queue = [];
  58. this._childMarkerEventHandlers = {
  59. 'dragstart': this._childMarkerDragStart,
  60. 'move': this._childMarkerMoved,
  61. 'dragend': this._childMarkerDragEnd,
  62. };
  63. // Hook the appropriate animation methods.
  64. var animate = BM.DomUtil.TRANSITION && this.options.animate;
  65. BM.extend(this, animate ? this._withAnimation : this._noAnimation);
  66. // Remember which MarkerCluster class to instantiate (animated or not).
  67. this._markerCluster = animate ? BM.MarkerCluster : BM.MarkerClusterNonAnimated;
  68. },
  69. addLayer: function (layer) {
  70. if (layer instanceof BM.LayerGroup) {
  71. return this.addLayers([layer]);
  72. }
  73. //Don't cluster non point data
  74. if (!layer.getLatLng) {
  75. this._nonPointGroup.addLayer(layer);
  76. this.fire('layeradd', {
  77. layer: layer
  78. });
  79. return this;
  80. }
  81. if (!this._map) {
  82. this._needsClustering.push(layer);
  83. this.fire('layeradd', {
  84. layer: layer
  85. });
  86. return this;
  87. }
  88. if (this.hasLayer(layer)) {
  89. return this;
  90. }
  91. //If we have already clustered we'll need to add this one to a cluster
  92. if (this._unspiderfy) {
  93. this._unspiderfy();
  94. }
  95. this._addLayer(layer, this._maxZoom);
  96. this.fire('layeradd', {
  97. layer: layer
  98. });
  99. // Refresh bounds and weighted positions.
  100. this._topClusterLevel._recalculateBounds();
  101. this._refreshClustersIcons();
  102. //Work out what is visible
  103. var visibleLayer = layer,
  104. currentZoom = this._zoom;
  105. if (layer.__parent) {
  106. while (visibleLayer.__parent._zoom >= currentZoom) {
  107. visibleLayer = visibleLayer.__parent;
  108. }
  109. }
  110. if (this._currentShownBounds.contains(visibleLayer.getLatLng())) {
  111. if (this.options.animateAddingMarkers) {
  112. this._animationAddLayer(layer, visibleLayer);
  113. } else {
  114. this._animationAddLayerNonAnimated(layer, visibleLayer);
  115. }
  116. }
  117. return this;
  118. },
  119. removeLayer: function (layer) {
  120. if (layer instanceof BM.LayerGroup) {
  121. return this.removeLayers([layer]);
  122. }
  123. //Non point layers
  124. if (!layer.getLatLng) {
  125. this._nonPointGroup.removeLayer(layer);
  126. this.fire('layerremove', {
  127. layer: layer
  128. });
  129. return this;
  130. }
  131. if (!this._map) {
  132. if (!this._arraySplice(this._needsClustering, layer) && this.hasLayer(layer)) {
  133. this._needsRemoving.push({
  134. layer: layer,
  135. latlng: layer._latlng
  136. });
  137. }
  138. this.fire('layerremove', {
  139. layer: layer
  140. });
  141. return this;
  142. }
  143. if (!layer.__parent) {
  144. return this;
  145. }
  146. if (this._unspiderfy) {
  147. this._unspiderfy();
  148. this._unspiderfyLayer(layer);
  149. }
  150. //Remove the marker from clusters
  151. this._removeLayer(layer, true);
  152. this.fire('layerremove', {
  153. layer: layer
  154. });
  155. // Refresh bounds and weighted positions.
  156. this._topClusterLevel._recalculateBounds();
  157. this._refreshClustersIcons();
  158. layer.off(this._childMarkerEventHandlers, this);
  159. if (this._featureGroup.hasLayer(layer)) {
  160. this._featureGroup.removeLayer(layer);
  161. if (layer.clusterShow) {
  162. layer.clusterShow();
  163. }
  164. }
  165. return this;
  166. },
  167. //Takes an array of markers and adds them in bulk
  168. addLayers: function (layersArray, skipLayerAddEvent) {
  169. if (!BM.Util.isArray(layersArray)) {
  170. return this.addLayer(layersArray);
  171. }
  172. var fg = this._featureGroup,
  173. npg = this._nonPointGroup,
  174. chunked = this.options.chunkedLoading,
  175. chunkInterval = this.options.chunkInterval,
  176. chunkProgress = this.options.chunkProgress,
  177. l = layersArray.length,
  178. offset = 0,
  179. originalArray = true,
  180. m;
  181. if (this._map) {
  182. var started = (new Date()).getTime();
  183. var process = BM.bind(function () {
  184. var start = (new Date()).getTime();
  185. for (; offset < l; offset++) {
  186. if (chunked && offset % 200 === 0) {
  187. // every couple hundred markers, instrument the time elapsed since processing started:
  188. var elapsed = (new Date()).getTime() - start;
  189. if (elapsed > chunkInterval) {
  190. break; // been working too hard, time to take a break :-)
  191. }
  192. }
  193. m = layersArray[offset];
  194. // Group of layers, append children to layersArray and skip.
  195. // Side effects:
  196. // - Total increases, so chunkProgress ratio jumps backward.
  197. // - Groups are not included in this group, only their non-group child layers (hasLayer).
  198. // Changing array length while looping does not affect performance in current browsers:
  199. // http://jsperf.com/for-loop-changing-length/6
  200. if (m instanceof BM.LayerGroup) {
  201. if (originalArray) {
  202. layersArray = layersArray.slice();
  203. originalArray = false;
  204. }
  205. this._extractNonGroupLayers(m, layersArray);
  206. l = layersArray.length;
  207. continue;
  208. }
  209. //Not point data, can't be clustered
  210. if (!m.getLatLng) {
  211. npg.addLayer(m);
  212. if (!skipLayerAddEvent) {
  213. this.fire('layeradd', {
  214. layer: m
  215. });
  216. }
  217. continue;
  218. }
  219. if (this.hasLayer(m)) {
  220. continue;
  221. }
  222. this._addLayer(m, this._maxZoom);
  223. if (!skipLayerAddEvent) {
  224. this.fire('layeradd', {
  225. layer: m
  226. });
  227. }
  228. //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will
  229. if (m.__parent) {
  230. if (m.__parent.getChildCount() === 2) {
  231. var markers = m.__parent.getAllChildMarkers(),
  232. otherMarker = markers[0] === m ? markers[1] : markers[0];
  233. fg.removeLayer(otherMarker);
  234. }
  235. }
  236. }
  237. if (chunkProgress) {
  238. // report progress and time elapsed:
  239. chunkProgress(offset, l, (new Date()).getTime() - started);
  240. }
  241. // Completed processing all markers.
  242. if (offset === l) {
  243. // Refresh bounds and weighted positions.
  244. this._topClusterLevel._recalculateBounds();
  245. this._refreshClustersIcons();
  246. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
  247. } else {
  248. setTimeout(process, this.options.chunkDelay);
  249. }
  250. }, this);
  251. process();
  252. } else {
  253. var needsClustering = this._needsClustering;
  254. for (; offset < l; offset++) {
  255. m = layersArray[offset];
  256. // Group of layers, append children to layersArray and skip.
  257. if (m instanceof BM.LayerGroup) {
  258. if (originalArray) {
  259. layersArray = layersArray.slice();
  260. originalArray = false;
  261. }
  262. this._extractNonGroupLayers(m, layersArray);
  263. l = layersArray.length;
  264. continue;
  265. }
  266. //Not point data, can't be clustered
  267. if (!m.getLatLng) {
  268. npg.addLayer(m);
  269. continue;
  270. }
  271. if (this.hasLayer(m)) {
  272. continue;
  273. }
  274. needsClustering.push(m);
  275. }
  276. }
  277. return this;
  278. },
  279. //Takes an array of markers and removes them in bulk
  280. removeLayers: function (layersArray) {
  281. var i, m,
  282. l = layersArray.length,
  283. fg = this._featureGroup,
  284. npg = this._nonPointGroup,
  285. originalArray = true;
  286. if (!this._map) {
  287. for (i = 0; i < l; i++) {
  288. m = layersArray[i];
  289. // Group of layers, append children to layersArray and skip.
  290. if (m instanceof BM.LayerGroup) {
  291. if (originalArray) {
  292. layersArray = layersArray.slice();
  293. originalArray = false;
  294. }
  295. this._extractNonGroupLayers(m, layersArray);
  296. l = layersArray.length;
  297. continue;
  298. }
  299. this._arraySplice(this._needsClustering, m);
  300. npg.removeLayer(m);
  301. if (this.hasLayer(m)) {
  302. this._needsRemoving.push({
  303. layer: m,
  304. latlng: m._latlng
  305. });
  306. }
  307. this.fire('layerremove', {
  308. layer: m
  309. });
  310. }
  311. return this;
  312. }
  313. if (this._unspiderfy) {
  314. this._unspiderfy();
  315. // Work on a copy of the array, so that next loop is not affected.
  316. var layersArray2 = layersArray.slice(),
  317. l2 = l;
  318. for (i = 0; i < l2; i++) {
  319. m = layersArray2[i];
  320. // Group of layers, append children to layersArray and skip.
  321. if (m instanceof BM.LayerGroup) {
  322. this._extractNonGroupLayers(m, layersArray2);
  323. l2 = layersArray2.length;
  324. continue;
  325. }
  326. this._unspiderfyLayer(m);
  327. }
  328. }
  329. for (i = 0; i < l; i++) {
  330. m = layersArray[i];
  331. // Group of layers, append children to layersArray and skip.
  332. if (m instanceof BM.LayerGroup) {
  333. if (originalArray) {
  334. layersArray = layersArray.slice();
  335. originalArray = false;
  336. }
  337. this._extractNonGroupLayers(m, layersArray);
  338. l = layersArray.length;
  339. continue;
  340. }
  341. if (!m.__parent) {
  342. npg.removeLayer(m);
  343. this.fire('layerremove', {
  344. layer: m
  345. });
  346. continue;
  347. }
  348. this._removeLayer(m, true, true);
  349. this.fire('layerremove', {
  350. layer: m
  351. });
  352. if (fg.hasLayer(m)) {
  353. fg.removeLayer(m);
  354. if (m.clusterShow) {
  355. m.clusterShow();
  356. }
  357. }
  358. }
  359. // Refresh bounds and weighted positions.
  360. this._topClusterLevel._recalculateBounds();
  361. this._refreshClustersIcons();
  362. //Fix up the clusters and markers on the map
  363. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
  364. return this;
  365. },
  366. //Removes all layers from the MarkerClusterGroup
  367. clearLayers: function () {
  368. //Need our own special implementation as the LayerGroup one doesn't work for us
  369. //If we aren't on the map (yet), blow away the markers we know of
  370. if (!this._map) {
  371. this._needsClustering = [];
  372. this._needsRemoving = [];
  373. delete this._gridClusters;
  374. delete this._gridUnclustered;
  375. }
  376. if (this._noanimationUnspiderfy) {
  377. this._noanimationUnspiderfy();
  378. }
  379. //Remove all the visible layers
  380. this._featureGroup.clearLayers();
  381. this._nonPointGroup.clearLayers();
  382. this.eachLayer(function (marker) {
  383. marker.off(this._childMarkerEventHandlers, this);
  384. delete marker.__parent;
  385. }, this);
  386. if (this._map) {
  387. //Reset _topClusterLevel and the DistanceGrids
  388. this._generateInitialClusters();
  389. }
  390. return this;
  391. },
  392. //Override FeatureGroup.getBounds as it doesn't work
  393. getBounds: function () {
  394. var bounds = new BM.LatLngBounds();
  395. if (this._topClusterLevel) {
  396. bounds.extend(this._topClusterLevel._bounds);
  397. }
  398. for (var i = this._needsClustering.length - 1; i >= 0; i--) {
  399. bounds.extend(this._needsClustering[i].getLatLng());
  400. }
  401. bounds.extend(this._nonPointGroup.getBounds());
  402. return bounds;
  403. },
  404. //Overrides LayerGroup.eachLayer
  405. eachLayer: function (method, context) {
  406. var markers = this._needsClustering.slice(),
  407. needsRemoving = this._needsRemoving,
  408. thisNeedsRemoving, i, j;
  409. if (this._topClusterLevel) {
  410. this._topClusterLevel.getAllChildMarkers(markers);
  411. }
  412. for (i = markers.length - 1; i >= 0; i--) {
  413. thisNeedsRemoving = true;
  414. for (j = needsRemoving.length - 1; j >= 0; j--) {
  415. if (needsRemoving[j].layer === markers[i]) {
  416. thisNeedsRemoving = false;
  417. break;
  418. }
  419. }
  420. if (thisNeedsRemoving) {
  421. method.call(context, markers[i]);
  422. }
  423. }
  424. this._nonPointGroup.eachLayer(method, context);
  425. },
  426. //Overrides LayerGroup.getLayers
  427. getLayers: function () {
  428. var layers = [];
  429. this.eachLayer(function (l) {
  430. layers.push(l);
  431. });
  432. return layers;
  433. },
  434. //Overrides LayerGroup.getLayer, WARNING: Really bad performance
  435. getLayer: function (id) {
  436. var result = null;
  437. id = parseInt(id, 10);
  438. this.eachLayer(function (l) {
  439. if (BM.stamp(l) === id) {
  440. result = l;
  441. }
  442. });
  443. return result;
  444. },
  445. //Returns true if the given layer is in this MarkerClusterGroup
  446. hasLayer: function (layer) {
  447. if (!layer) {
  448. return false;
  449. }
  450. var i, anArray = this._needsClustering;
  451. for (i = anArray.length - 1; i >= 0; i--) {
  452. if (anArray[i] === layer) {
  453. return true;
  454. }
  455. }
  456. anArray = this._needsRemoving;
  457. for (i = anArray.length - 1; i >= 0; i--) {
  458. if (anArray[i].layer === layer) {
  459. return false;
  460. }
  461. }
  462. return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer);
  463. },
  464. //Zoom down to show the given layer (spiderfying if necessary) then calls the callback
  465. zoomToShowLayer: function (layer, callback) {
  466. if (typeof callback !== 'function') {
  467. callback = function () {};
  468. }
  469. var showMarker = function () {
  470. if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) {
  471. this._map.off('moveend', showMarker, this);
  472. this.off('animationend', showMarker, this);
  473. if (layer._icon) {
  474. callback();
  475. } else if (layer.__parent._icon) {
  476. this.once('spiderfied', callback, this);
  477. layer.__parent.spiderfy();
  478. }
  479. }
  480. };
  481. if (layer._icon && this._map.getBounds().contains(layer.getLatLng())) {
  482. //Layer is visible ond on screen, immediate return
  483. callback();
  484. } else if (layer.__parent._zoom < Math.round(this._map._zoom)) {
  485. //Layer should be visible at this zoom level. It must not be on screen so just pan over to it
  486. this._map.on('moveend', showMarker, this);
  487. this._map.panTo(layer.getLatLng());
  488. } else {
  489. this._map.on('moveend', showMarker, this);
  490. this.on('animationend', showMarker, this);
  491. layer.__parent.zoomToBounds();
  492. }
  493. },
  494. //Overrides FeatureGroup.onAdd
  495. onAdd: function (map) {
  496. this._map = map;
  497. var i, l, layer;
  498. if (!isFinite(this._map.getMaxZoom())) {
  499. throw "Map has no maxZoom specified";
  500. }
  501. this._featureGroup.addTo(map);
  502. this._nonPointGroup.addTo(map);
  503. if (!this._gridClusters) {
  504. this._generateInitialClusters();
  505. }
  506. this._maxLat = map.options.crs.projection.MAX_LATITUDE;
  507. //Restore all the positions as they are in the MCG before removing them
  508. for (i = 0, l = this._needsRemoving.length; i < l; i++) {
  509. layer = this._needsRemoving[i];
  510. layer.newlatlng = layer.layer._latlng;
  511. layer.layer._latlng = layer.latlng;
  512. }
  513. //Remove them, then restore their new positions
  514. for (i = 0, l = this._needsRemoving.length; i < l; i++) {
  515. layer = this._needsRemoving[i];
  516. this._removeLayer(layer.layer, true);
  517. layer.layer._latlng = layer.newlatlng;
  518. }
  519. this._needsRemoving = [];
  520. //Remember the current zoom level and bounds
  521. this._zoom = Math.round(this._map._zoom);
  522. this._currentShownBounds = this._getExpandedVisibleBounds();
  523. this._map.on('zoomend', this._zoomEnd, this);
  524. this._map.on('moveend', this._moveEnd, this);
  525. if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
  526. this._spiderfierOnAdd();
  527. }
  528. this._bindEvents();
  529. //Actually add our markers to the map:
  530. l = this._needsClustering;
  531. this._needsClustering = [];
  532. this.addLayers(l, true);
  533. },
  534. //Overrides FeatureGroup.onRemove
  535. onRemove: function (map) {
  536. map.off('zoomend', this._zoomEnd, this);
  537. map.off('moveend', this._moveEnd, this);
  538. this._unbindEvents();
  539. //In case we are in a cluster animation
  540. this._map._mapPane.className = this._map._mapPane.className.replace(' bigemap-cluster-anim', '');
  541. if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
  542. this._spiderfierOnRemove();
  543. }
  544. delete this._maxLat;
  545. //Clean up all the layers we added to the map
  546. this._hideCoverage();
  547. this._featureGroup.remove();
  548. this._nonPointGroup.remove();
  549. this._featureGroup.clearLayers();
  550. this._map = null;
  551. },
  552. getVisibleParent: function (marker) {
  553. var vMarker = marker;
  554. while (vMarker && !vMarker._icon) {
  555. vMarker = vMarker.__parent;
  556. }
  557. return vMarker || null;
  558. },
  559. //Remove the given object from the given array
  560. _arraySplice: function (anArray, obj) {
  561. for (var i = anArray.length - 1; i >= 0; i--) {
  562. if (anArray[i] === obj) {
  563. anArray.splice(i, 1);
  564. return true;
  565. }
  566. }
  567. },
  568. /**
  569. * Removes a marker from all _gridUnclustered zoom levels, starting at the supplied zoom.
  570. * @param marker to be removed from _gridUnclustered.
  571. * @param z integer bottom start zoom level (included)
  572. * @private
  573. */
  574. _removeFromGridUnclustered: function (marker, z) {
  575. var map = this._map,
  576. gridUnclustered = this._gridUnclustered,
  577. minZoom = Math.floor(this._map.getMinZoom());
  578. for (; z >= minZoom; z--) {
  579. if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) {
  580. break;
  581. }
  582. }
  583. },
  584. _childMarkerDragStart: function (e) {
  585. e.target.__dragStart = e.target._latlng;
  586. },
  587. _childMarkerMoved: function (e) {
  588. if (!this._ignoreMove && !e.target.__dragStart) {
  589. var isPopupOpen = e.target._popup && e.target._popup.isOpen();
  590. this._moveChild(e.target, e.oldLatLng, e.latlng);
  591. if (isPopupOpen) {
  592. e.target.openPopup();
  593. }
  594. }
  595. },
  596. _moveChild: function (layer, from, to) {
  597. layer._latlng = from;
  598. this.removeLayer(layer);
  599. layer._latlng = to;
  600. this.addLayer(layer);
  601. },
  602. _childMarkerDragEnd: function (e) {
  603. var dragStart = e.target.__dragStart;
  604. delete e.target.__dragStart;
  605. if (dragStart) {
  606. this._moveChild(e.target, dragStart, e.target._latlng);
  607. }
  608. },
  609. //Internal function for removing a marker from everything.
  610. //dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions)
  611. _removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) {
  612. var gridClusters = this._gridClusters,
  613. gridUnclustered = this._gridUnclustered,
  614. fg = this._featureGroup,
  615. map = this._map,
  616. minZoom = Math.floor(this._map.getMinZoom());
  617. //Remove the marker from distance clusters it might be in
  618. if (removeFromDistanceGrid) {
  619. this._removeFromGridUnclustered(marker, this._maxZoom);
  620. }
  621. //Work our way up the clusters removing them as we go if required
  622. var cluster = marker.__parent,
  623. markers = cluster._markers,
  624. otherMarker;
  625. //Remove the marker from the immediate parents marker list
  626. this._arraySplice(markers, marker);
  627. while (cluster) {
  628. cluster._childCount--;
  629. cluster._boundsNeedUpdate = true;
  630. if (cluster._zoom < minZoom) {
  631. //Top level, do nothing
  632. break;
  633. } else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required
  634. //We need to push the other marker up to the parent
  635. otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0];
  636. //Update distance grid
  637. gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom));
  638. gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom));
  639. //Move otherMarker up to parent
  640. this._arraySplice(cluster.__parent._childClusters, cluster);
  641. cluster.__parent._markers.push(otherMarker);
  642. otherMarker.__parent = cluster.__parent;
  643. if (cluster._icon) {
  644. //Cluster is currently on the map, need to put the marker on the map instead
  645. fg.removeLayer(cluster);
  646. if (!dontUpdateMap) {
  647. fg.addLayer(otherMarker);
  648. }
  649. }
  650. } else {
  651. cluster._iconNeedsUpdate = true;
  652. }
  653. cluster = cluster.__parent;
  654. }
  655. delete marker.__parent;
  656. },
  657. _isOrIsParent: function (el, oel) {
  658. while (oel) {
  659. if (el === oel) {
  660. return true;
  661. }
  662. oel = oel.parentNode;
  663. }
  664. return false;
  665. },
  666. //Override BM.Evented.fire
  667. fire: function (type, data, propagate) {
  668. if (data && data.layer instanceof BM.MarkerCluster) {
  669. //Prevent multiple clustermouseover/off events if the icon is made up of stacked divs (Doesn't work in ie <= 8, no relatedTarget)
  670. if (data.originalEvent && this._isOrIsParent(data.layer._icon, data.originalEvent.relatedTarget)) {
  671. return;
  672. }
  673. type = 'cluster' + type;
  674. }
  675. BM.FeatureGroup.prototype.fire.call(this, type, data, propagate);
  676. },
  677. //Override BM.Evented.listens
  678. listens: function (type, propagate) {
  679. return BM.FeatureGroup.prototype.listens.call(this, type, propagate) || BM.FeatureGroup.prototype.listens.call(this, 'cluster' + type, propagate);
  680. },
  681. //Default functionality
  682. _defaultIconCreateFunction: function (cluster) {
  683. var childCount = cluster.getChildCount();
  684. var c = ' marker-cluster-';
  685. if (childCount < 10) {
  686. c += 'small';
  687. } else if (childCount < 100) {
  688. c += 'medium';
  689. } else {
  690. c += 'large';
  691. }
  692. return new BM.DivIcon({
  693. html: '<div><span>' + childCount + '</span></div>',
  694. className: 'marker-cluster' + c,
  695. iconSize: new BM.Point(40, 40)
  696. });
  697. },
  698. _bindEvents: function () {
  699. var map = this._map,
  700. spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
  701. showCoverageOnHover = this.options.showCoverageOnHover,
  702. zoomToBoundsOnClick = this.options.zoomToBoundsOnClick;
  703. //Zoom on cluster click or spiderfy if we are at the lowest level
  704. if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
  705. this.on('clusterclick', this._zoomOrSpiderfy, this);
  706. }
  707. //Show convex hull (boundary) polygon on mouse over
  708. if (showCoverageOnHover) {
  709. this.on('clustermouseover', this._showCoverage, this);
  710. this.on('clustermouseout', this._hideCoverage, this);
  711. map.on('zoomend', this._hideCoverage, this);
  712. }
  713. },
  714. _zoomOrSpiderfy: function (e) {
  715. var cluster = e.layer,
  716. bottomCluster = cluster;
  717. while (bottomCluster._childClusters.length === 1) {
  718. bottomCluster = bottomCluster._childClusters[0];
  719. }
  720. if (bottomCluster._zoom === this._maxZoom &&
  721. bottomCluster._childCount === cluster._childCount &&
  722. this.options.spiderfyOnMaxZoom) {
  723. // All child markers are contained in a single cluster from this._maxZoom to this cluster.
  724. cluster.spiderfy();
  725. } else if (this.options.zoomToBoundsOnClick) {
  726. cluster.zoomToBounds();
  727. }
  728. // Focus the map again for keyboard users.
  729. if (e.originalEvent && e.originalEvent.keyCode === 13) {
  730. this._map._container.focus();
  731. }
  732. },
  733. _showCoverage: function (e) {
  734. var map = this._map;
  735. if (this._inZoomAnimation) {
  736. return;
  737. }
  738. if (this._shownPolygon) {
  739. map.removeLayer(this._shownPolygon);
  740. }
  741. if (e.layer.getChildCount() > 2 && e.layer !== this._spiderfied) {
  742. this._shownPolygon = new BM.Polygon(e.layer.getConvexHull(), this.options.polygonOptions);
  743. map.addLayer(this._shownPolygon);
  744. }
  745. },
  746. _hideCoverage: function () {
  747. if (this._shownPolygon) {
  748. this._map.removeLayer(this._shownPolygon);
  749. this._shownPolygon = null;
  750. }
  751. },
  752. _unbindEvents: function () {
  753. var spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
  754. showCoverageOnHover = this.options.showCoverageOnHover,
  755. zoomToBoundsOnClick = this.options.zoomToBoundsOnClick,
  756. map = this._map;
  757. if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
  758. this.off('clusterclick', this._zoomOrSpiderfy, this);
  759. }
  760. if (showCoverageOnHover) {
  761. this.off('clustermouseover', this._showCoverage, this);
  762. this.off('clustermouseout', this._hideCoverage, this);
  763. map.off('zoomend', this._hideCoverage, this);
  764. }
  765. },
  766. _zoomEnd: function () {
  767. if (!this._map) { //May have been removed from the map by a zoomEnd handler
  768. return;
  769. }
  770. this._mergeSplitClusters();
  771. this._zoom = Math.round(this._map._zoom);
  772. this._currentShownBounds = this._getExpandedVisibleBounds();
  773. },
  774. _moveEnd: function () {
  775. if (this._inZoomAnimation) {
  776. return;
  777. }
  778. var newBounds = this._getExpandedVisibleBounds();
  779. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, Math.floor(this._map.getMinZoom()), this._zoom, newBounds);
  780. this._topClusterLevel._recursivelyAddChildrenToMap(null, Math.round(this._map._zoom), newBounds);
  781. this._currentShownBounds = newBounds;
  782. return;
  783. },
  784. _generateInitialClusters: function () {
  785. var maxZoom = Math.ceil(this._map.getMaxZoom()),
  786. minZoom = Math.floor(this._map.getMinZoom()),
  787. radius = this.options.maxClusterRadius,
  788. radiusFn = radius;
  789. //If we just set maxClusterRadius to a single number, we need to create
  790. //a simple function to return that number. Otherwise, we just have to
  791. //use the function we've passed in.
  792. if (typeof radius !== "function") {
  793. radiusFn = function () {
  794. return radius;
  795. };
  796. }
  797. if (this.options.disableClusteringAtZoom !== null) {
  798. maxZoom = this.options.disableClusteringAtZoom - 1;
  799. }
  800. this._maxZoom = maxZoom;
  801. this._gridClusters = {};
  802. this._gridUnclustered = {};
  803. //Set up DistanceGrids for each zoom
  804. for (var zoom = maxZoom; zoom >= minZoom; zoom--) {
  805. this._gridClusters[zoom] = new BM.DistanceGrid(radiusFn(zoom));
  806. this._gridUnclustered[zoom] = new BM.DistanceGrid(radiusFn(zoom));
  807. }
  808. // Instantiate the appropriate BM.MarkerCluster class (animated or not).
  809. this._topClusterLevel = new this._markerCluster(this, minZoom - 1);
  810. },
  811. //Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom)
  812. _addLayer: function (layer, zoom) {
  813. var gridClusters = this._gridClusters,
  814. gridUnclustered = this._gridUnclustered,
  815. minZoom = Math.floor(this._map.getMinZoom()),
  816. markerPoint, z;
  817. if (this.options.singleMarkerMode) {
  818. this._overrideMarkerIcon(layer);
  819. }
  820. layer.on(this._childMarkerEventHandlers, this);
  821. //Find the lowest zoom level to slot this one in
  822. for (; zoom >= minZoom; zoom--) {
  823. markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position
  824. //Try find a cluster close by
  825. var closest = gridClusters[zoom].getNearObject(markerPoint);
  826. if (closest) {
  827. closest._addChild(layer);
  828. layer.__parent = closest;
  829. return;
  830. }
  831. //Try find a marker close by to form a new cluster with
  832. closest = gridUnclustered[zoom].getNearObject(markerPoint);
  833. if (closest) {
  834. var parent = closest.__parent;
  835. if (parent) {
  836. this._removeLayer(closest, false);
  837. }
  838. //Create new cluster with these 2 in it
  839. var newCluster = new this._markerCluster(this, zoom, closest, layer);
  840. gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom));
  841. closest.__parent = newCluster;
  842. layer.__parent = newCluster;
  843. //First create any new intermediate parent clusters that don't exist
  844. var lastParent = newCluster;
  845. for (z = zoom - 1; z > parent._zoom; z--) {
  846. lastParent = new this._markerCluster(this, z, lastParent);
  847. gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z));
  848. }
  849. parent._addChild(lastParent);
  850. //Remove closest from this zoom level and any above that it is in, replace with newCluster
  851. this._removeFromGridUnclustered(closest, zoom);
  852. return;
  853. }
  854. //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards
  855. gridUnclustered[zoom].addObject(layer, markerPoint);
  856. }
  857. //Didn't get in anything, add us to the top
  858. this._topClusterLevel._addChild(layer);
  859. layer.__parent = this._topClusterLevel;
  860. return;
  861. },
  862. /**
  863. * Refreshes the icon of all "dirty" visible clusters.
  864. * Non-visible "dirty" clusters will be updated when they are added to the map.
  865. * @private
  866. */
  867. _refreshClustersIcons: function () {
  868. this._featureGroup.eachLayer(function (c) {
  869. if (c instanceof BM.MarkerCluster && c._iconNeedsUpdate) {
  870. c._updateIcon();
  871. }
  872. });
  873. },
  874. //Enqueue code to fire after the marker expand/contract has happened
  875. _enqueue: function (fn) {
  876. this._queue.push(fn);
  877. if (!this._queueTimeout) {
  878. this._queueTimeout = setTimeout(BM.bind(this._processQueue, this), 300);
  879. }
  880. },
  881. _processQueue: function () {
  882. for (var i = 0; i < this._queue.length; i++) {
  883. this._queue[i].call(this);
  884. }
  885. this._queue.length = 0;
  886. clearTimeout(this._queueTimeout);
  887. this._queueTimeout = null;
  888. },
  889. //Merge and split any existing clusters that are too big or small
  890. _mergeSplitClusters: function () {
  891. var mapZoom = Math.round(this._map._zoom);
  892. //In case we are starting to split before the animation finished
  893. this._processQueue();
  894. if (this._zoom < mapZoom && this._currentShownBounds.intersects(this._getExpandedVisibleBounds())) { //Zoom in, split
  895. this._animationStart();
  896. //Remove clusters now off screen
  897. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, Math.floor(this._map.getMinZoom()), this._zoom, this._getExpandedVisibleBounds());
  898. this._animationZoomIn(this._zoom, mapZoom);
  899. } else if (this._zoom > mapZoom) { //Zoom out, merge
  900. this._animationStart();
  901. this._animationZoomOut(this._zoom, mapZoom);
  902. } else {
  903. this._moveEnd();
  904. }
  905. },
  906. //Gets the maps visible bounds expanded in each direction by the size of the screen (so the user cannot see an area we do not cover in one pan)
  907. _getExpandedVisibleBounds: function () {
  908. if (!this.options.removeOutsideVisibleBounds) {
  909. return this._mapBoundsInfinite;
  910. } else if (BM.Browser.mobile) {
  911. return this._checkBoundsMaxLat(this._map.getBounds());
  912. }
  913. return this._checkBoundsMaxLat(this._map.getBounds().pad(1)); // Padding expands the bounds by its own dimensions but scaled with the given factor.
  914. },
  915. /**
  916. * Expands the latitude to Infinity (or -Infinity) if the input bounds reach the map projection maximum defined latitude
  917. * (in the case of Web/Spherical Mercator, it is 85.0511287798 / see https://en.wikipedia.org/wiki/Web_Mercator#Formulas).
  918. * Otherwise, the removeOutsideVisibleBounds option will remove markers beyond that limit, whereas the same markers without
  919. * this option (or outside MCG) will have their position floored (ceiled) by the projection and rendered at that limit,
  920. * making the user think that MCG "eats" them and never displays them again.
  921. * @param bounds BM.LatLngBounds
  922. * @returns {BM.LatLngBounds}
  923. * @private
  924. */
  925. _checkBoundsMaxLat: function (bounds) {
  926. var maxLat = this._maxLat;
  927. if (maxLat !== undefined) {
  928. if (bounds.getNorth() >= maxLat) {
  929. bounds._northEast.lat = Infinity;
  930. }
  931. if (bounds.getSouth() <= -maxLat) {
  932. bounds._southWest.lat = -Infinity;
  933. }
  934. }
  935. return bounds;
  936. },
  937. //Shared animation code
  938. _animationAddLayerNonAnimated: function (layer, newCluster) {
  939. if (newCluster === layer) {
  940. this._featureGroup.addLayer(layer);
  941. } else if (newCluster._childCount === 2) {
  942. newCluster._addToMap();
  943. var markers = newCluster.getAllChildMarkers();
  944. this._featureGroup.removeLayer(markers[0]);
  945. this._featureGroup.removeLayer(markers[1]);
  946. } else {
  947. newCluster._updateIcon();
  948. }
  949. },
  950. /**
  951. * Extracts individual (i.e. non-group) layers from a Layer Group.
  952. * @param group to extract layers from.
  953. * @param output {Array} in which to store the extracted layers.
  954. * @returns {*|Array}
  955. * @private
  956. */
  957. _extractNonGroupLayers: function (group, output) {
  958. var layers = group.getLayers(),
  959. i = 0,
  960. layer;
  961. output = output || [];
  962. for (; i < layers.length; i++) {
  963. layer = layers[i];
  964. if (layer instanceof BM.LayerGroup) {
  965. this._extractNonGroupLayers(layer, output);
  966. continue;
  967. }
  968. output.push(layer);
  969. }
  970. return output;
  971. },
  972. /**
  973. * Implements the singleMarkerMode option.
  974. * @param layer Marker to re-style using the Clusters iconCreateFunction.
  975. * @returns {BM.Icon} The newly created icon.
  976. * @private
  977. */
  978. _overrideMarkerIcon: function (layer) {
  979. var icon = layer.options.icon = this.options.iconCreateFunction({
  980. getChildCount: function () {
  981. return 1;
  982. },
  983. getAllChildMarkers: function () {
  984. return [layer];
  985. }
  986. });
  987. return icon;
  988. }
  989. });
  990. // Constant bounds used in case option "removeOutsideVisibleBounds" is set to false.
  991. BM.MarkerClusterGroup.include({
  992. _mapBoundsInfinite: new BM.LatLngBounds(new BM.LatLng(-Infinity, -Infinity), new BM.LatLng(Infinity, Infinity))
  993. });
  994. BM.MarkerClusterGroup.include({
  995. _noAnimation: {
  996. //Non Animated versions of everything
  997. _animationStart: function () {
  998. //Do nothing...
  999. },
  1000. _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
  1001. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, Math.floor(this._map.getMinZoom()), previousZoomLevel);
  1002. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  1003. //We didn't actually animate, but we use this event to mean "clustering animations have finished"
  1004. this.fire('animationend');
  1005. },
  1006. _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
  1007. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, Math.floor(this._map.getMinZoom()), previousZoomLevel);
  1008. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  1009. //We didn't actually animate, but we use this event to mean "clustering animations have finished"
  1010. this.fire('animationend');
  1011. },
  1012. _animationAddLayer: function (layer, newCluster) {
  1013. this._animationAddLayerNonAnimated(layer, newCluster);
  1014. }
  1015. },
  1016. _withAnimation: {
  1017. //Animated versions here
  1018. _animationStart: function () {
  1019. this._map._mapPane.className += ' bigemap-cluster-anim';
  1020. this._inZoomAnimation++;
  1021. },
  1022. _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
  1023. var bounds = this._getExpandedVisibleBounds(),
  1024. fg = this._featureGroup,
  1025. minZoom = Math.floor(this._map.getMinZoom()),
  1026. i;
  1027. this._ignoreMove = true;
  1028. //Add all children of current clusters to map and remove those clusters from map
  1029. this._topClusterLevel._recursively(bounds, previousZoomLevel, minZoom, function (c) {
  1030. var startPos = c._latlng,
  1031. markers = c._markers,
  1032. m;
  1033. if (!bounds.contains(startPos)) {
  1034. startPos = null;
  1035. }
  1036. if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us
  1037. fg.removeLayer(c);
  1038. c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds);
  1039. } else {
  1040. //Fade out old cluster
  1041. c.clusterHide();
  1042. c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds);
  1043. }
  1044. //Remove all markers that aren't visible any more
  1045. //TODO: Do we actually need to do this on the higher levels too?
  1046. for (i = markers.length - 1; i >= 0; i--) {
  1047. m = markers[i];
  1048. if (!bounds.contains(m._latlng)) {
  1049. fg.removeLayer(m);
  1050. }
  1051. }
  1052. });
  1053. this._forceLayout();
  1054. //Update opacities
  1055. this._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel);
  1056. //TODO Maybe? Update markers in _recursivelyBecomeVisible
  1057. fg.eachLayer(function (n) {
  1058. if (!(n instanceof BM.MarkerCluster) && n._icon) {
  1059. n.clusterShow();
  1060. }
  1061. });
  1062. //update the positions of the just added clusters/markers
  1063. this._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) {
  1064. c._recursivelyRestoreChildPositions(newZoomLevel);
  1065. });
  1066. this._ignoreMove = false;
  1067. //Remove the old clusters and close the zoom animation
  1068. this._enqueue(function () {
  1069. //update the positions of the just added clusters/markers
  1070. this._topClusterLevel._recursively(bounds, previousZoomLevel, minZoom, function (c) {
  1071. fg.removeLayer(c);
  1072. c.clusterShow();
  1073. });
  1074. this._animationEnd();
  1075. });
  1076. },
  1077. _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
  1078. this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel);
  1079. //Need to add markers for those that weren't on the map before but are now
  1080. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  1081. //Remove markers that were on the map before but won't be now
  1082. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, Math.floor(this._map.getMinZoom()), previousZoomLevel, this._getExpandedVisibleBounds());
  1083. },
  1084. _animationAddLayer: function (layer, newCluster) {
  1085. var me = this,
  1086. fg = this._featureGroup;
  1087. fg.addLayer(layer);
  1088. if (newCluster !== layer) {
  1089. if (newCluster._childCount > 2) { //Was already a cluster
  1090. newCluster._updateIcon();
  1091. this._forceLayout();
  1092. this._animationStart();
  1093. layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng()));
  1094. layer.clusterHide();
  1095. this._enqueue(function () {
  1096. fg.removeLayer(layer);
  1097. layer.clusterShow();
  1098. me._animationEnd();
  1099. });
  1100. } else { //Just became a cluster
  1101. this._forceLayout();
  1102. me._animationStart();
  1103. me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._zoom);
  1104. }
  1105. }
  1106. }
  1107. },
  1108. // Private methods for animated versions.
  1109. _animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) {
  1110. var bounds = this._getExpandedVisibleBounds(),
  1111. minZoom = Math.floor(this._map.getMinZoom());
  1112. //Animate all of the markers in the clusters to move to their cluster center point
  1113. cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, minZoom, previousZoomLevel + 1, newZoomLevel);
  1114. var me = this;
  1115. //Update the opacity (If we immediately set it they won't animate)
  1116. this._forceLayout();
  1117. cluster._recursivelyBecomeVisible(bounds, newZoomLevel);
  1118. //TODO: Maybe use the transition timing stuff to make this more reliable
  1119. //When the animations are done, tidy up
  1120. this._enqueue(function () {
  1121. //This cluster stopped being a cluster before the timeout fired
  1122. if (cluster._childCount === 1) {
  1123. var m = cluster._markers[0];
  1124. //If we were in a cluster animation at the time then the opacity and position of our child could be wrong now, so fix it
  1125. this._ignoreMove = true;
  1126. m.setLatLng(m.getLatLng());
  1127. this._ignoreMove = false;
  1128. if (m.clusterShow) {
  1129. m.clusterShow();
  1130. }
  1131. } else {
  1132. cluster._recursively(bounds, newZoomLevel, minZoom, function (c) {
  1133. c._recursivelyRemoveChildrenFromMap(bounds, minZoom, previousZoomLevel + 1);
  1134. });
  1135. }
  1136. me._animationEnd();
  1137. });
  1138. },
  1139. _animationEnd: function () {
  1140. if (this._map) {
  1141. this._map._mapPane.className = this._map._mapPane.className.replace(' bigemap-cluster-anim', '');
  1142. }
  1143. this._inZoomAnimation--;
  1144. this.fire('animationend');
  1145. },
  1146. //Force a browser layout of stuff in the map
  1147. // Should apply the current opacity and location to all elements so we can update them again for an animation
  1148. _forceLayout: function () {
  1149. //In my testing this works, infact offsetWidth of any element seems to work.
  1150. //Could loop all this._layers and do this for each _icon if it stops working
  1151. BM.Util.falseFn(document.body.offsetWidth);
  1152. }
  1153. });
  1154. BM.markerClusterGroup = function (options) {
  1155. return new BM.MarkerClusterGroup(options);
  1156. };
  1157. var MarkerCluster = BM.MarkerCluster = BM.Marker.extend({
  1158. options: BM.Icon.prototype.options,
  1159. initialize: function (group, zoom, a, b) {
  1160. BM.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new BM.LatLng(0, 0), {
  1161. icon: this,
  1162. pane: group.options.clusterPane
  1163. });
  1164. this._group = group;
  1165. this._zoom = zoom;
  1166. this._markers = [];
  1167. this._childClusters = [];
  1168. this._childCount = 0;
  1169. this._iconNeedsUpdate = true;
  1170. this._boundsNeedUpdate = true;
  1171. this._bounds = new BM.LatLngBounds();
  1172. if (a) {
  1173. this._addChild(a);
  1174. }
  1175. if (b) {
  1176. this._addChild(b);
  1177. }
  1178. },
  1179. //Recursively retrieve all child markers of this cluster
  1180. getAllChildMarkers: function (storageArray, ignoreDraggedMarker) {
  1181. storageArray = storageArray || [];
  1182. for (var i = this._childClusters.length - 1; i >= 0; i--) {
  1183. this._childClusters[i].getAllChildMarkers(storageArray);
  1184. }
  1185. for (var j = this._markers.length - 1; j >= 0; j--) {
  1186. if (ignoreDraggedMarker && this._markers[j].__dragStart) {
  1187. continue;
  1188. }
  1189. storageArray.push(this._markers[j]);
  1190. }
  1191. return storageArray;
  1192. },
  1193. //Returns the count of how many child markers we have
  1194. getChildCount: function () {
  1195. return this._childCount;
  1196. },
  1197. //Zoom to the minimum of showing all of the child markers, or the extents of this cluster
  1198. zoomToBounds: function (fitBoundsOptions) {
  1199. var childClusters = this._childClusters.slice(),
  1200. map = this._group._map,
  1201. boundsZoom = map.getBoundsZoom(this._bounds),
  1202. zoom = this._zoom + 1,
  1203. mapZoom = map.getZoom(),
  1204. i;
  1205. //calculate how far we need to zoom down to see all of the markers
  1206. while (childClusters.length > 0 && boundsZoom > zoom) {
  1207. zoom++;
  1208. var newClusters = [];
  1209. for (i = 0; i < childClusters.length; i++) {
  1210. newClusters = newClusters.concat(childClusters[i]._childClusters);
  1211. }
  1212. childClusters = newClusters;
  1213. }
  1214. if (boundsZoom > zoom) {
  1215. this._group._map.setView(this._latlng, zoom);
  1216. } else if (boundsZoom <= mapZoom) { //If fitBounds wouldn't zoom us down, zoom us down instead
  1217. this._group._map.setView(this._latlng, mapZoom + 1);
  1218. } else {
  1219. this._group._map.fitBounds(this._bounds, fitBoundsOptions);
  1220. }
  1221. },
  1222. getBounds: function () {
  1223. var bounds = new BM.LatLngBounds();
  1224. bounds.extend(this._bounds);
  1225. return bounds;
  1226. },
  1227. _updateIcon: function () {
  1228. this._iconNeedsUpdate = true;
  1229. if (this._icon) {
  1230. this.setIcon(this);
  1231. }
  1232. },
  1233. //Cludge for Icon, we pretend to be an icon for performance
  1234. createIcon: function () {
  1235. if (this._iconNeedsUpdate) {
  1236. this._iconObj = this._group.options.iconCreateFunction(this);
  1237. this._iconNeedsUpdate = false;
  1238. }
  1239. return this._iconObj.createIcon();
  1240. },
  1241. createShadow: function () {
  1242. return this._iconObj.createShadow();
  1243. },
  1244. _addChild: function (new1, isNotificationFromChild) {
  1245. this._iconNeedsUpdate = true;
  1246. this._boundsNeedUpdate = true;
  1247. this._setClusterCenter(new1);
  1248. if (new1 instanceof BM.MarkerCluster) {
  1249. if (!isNotificationFromChild) {
  1250. this._childClusters.push(new1);
  1251. new1.__parent = this;
  1252. }
  1253. this._childCount += new1._childCount;
  1254. } else {
  1255. if (!isNotificationFromChild) {
  1256. this._markers.push(new1);
  1257. }
  1258. this._childCount++;
  1259. }
  1260. if (this.__parent) {
  1261. this.__parent._addChild(new1, true);
  1262. }
  1263. },
  1264. /**
  1265. * Makes sure the cluster center is set. If not, uses the child center if it is a cluster, or the marker position.
  1266. * @param child BM.MarkerCluster|BM.Marker that will be used as cluster center if not defined yet.
  1267. * @private
  1268. */
  1269. _setClusterCenter: function (child) {
  1270. if (!this._cLatLng) {
  1271. // when clustering, take position of the first point as the cluster center
  1272. this._cLatLng = child._cLatLng || child._latlng;
  1273. }
  1274. },
  1275. /**
  1276. * Assigns impossible bounding values so that the next extend entirely determines the new bounds.
  1277. * This method avoids having to trash the previous BM.LatLngBounds object and to create a new one, which is much slower for this class.
  1278. * As long as the bounds are not extended, most other methods would probably fail, as they would with bounds initialized but not extended.
  1279. * @private
  1280. */
  1281. _resetBounds: function () {
  1282. var bounds = this._bounds;
  1283. if (bounds._southWest) {
  1284. bounds._southWest.lat = Infinity;
  1285. bounds._southWest.lng = Infinity;
  1286. }
  1287. if (bounds._northEast) {
  1288. bounds._northEast.lat = -Infinity;
  1289. bounds._northEast.lng = -Infinity;
  1290. }
  1291. },
  1292. _recalculateBounds: function () {
  1293. var markers = this._markers,
  1294. childClusters = this._childClusters,
  1295. latSum = 0,
  1296. lngSum = 0,
  1297. totalCount = this._childCount,
  1298. i, child, childLatLng, childCount;
  1299. // Case where all markers are removed from the map and we are left with just an empty _topClusterLevel.
  1300. if (totalCount === 0) {
  1301. return;
  1302. }
  1303. // Reset rather than creating a new object, for performance.
  1304. this._resetBounds();
  1305. // Child markers.
  1306. for (i = 0; i < markers.length; i++) {
  1307. childLatLng = markers[i]._latlng;
  1308. this._bounds.extend(childLatLng);
  1309. latSum += childLatLng.lat;
  1310. lngSum += childLatLng.lng;
  1311. }
  1312. // Child clusters.
  1313. for (i = 0; i < childClusters.length; i++) {
  1314. child = childClusters[i];
  1315. // Re-compute child bounds and weighted position first if necessary.
  1316. if (child._boundsNeedUpdate) {
  1317. child._recalculateBounds();
  1318. }
  1319. this._bounds.extend(child._bounds);
  1320. childLatLng = child._wLatLng;
  1321. childCount = child._childCount;
  1322. latSum += childLatLng.lat * childCount;
  1323. lngSum += childLatLng.lng * childCount;
  1324. }
  1325. this._latlng = this._wLatLng = new BM.LatLng(latSum / totalCount, lngSum / totalCount);
  1326. // Reset dirty flag.
  1327. this._boundsNeedUpdate = false;
  1328. },
  1329. //Set our markers position as given and add it to the map
  1330. _addToMap: function (startPos) {
  1331. if (startPos) {
  1332. this._backupLatlng = this._latlng;
  1333. this.setLatLng(startPos);
  1334. }
  1335. this._group._featureGroup.addLayer(this);
  1336. },
  1337. _recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) {
  1338. this._recursively(bounds, this._group._map.getMinZoom(), maxZoom - 1,
  1339. function (c) {
  1340. var markers = c._markers,
  1341. i, m;
  1342. for (i = markers.length - 1; i >= 0; i--) {
  1343. m = markers[i];
  1344. //Only do it if the icon is still on the map
  1345. if (m._icon) {
  1346. m._setPos(center);
  1347. m.clusterHide();
  1348. }
  1349. }
  1350. },
  1351. function (c) {
  1352. var childClusters = c._childClusters,
  1353. j, cm;
  1354. for (j = childClusters.length - 1; j >= 0; j--) {
  1355. cm = childClusters[j];
  1356. if (cm._icon) {
  1357. cm._setPos(center);
  1358. cm.clusterHide();
  1359. }
  1360. }
  1361. }
  1362. );
  1363. },
  1364. _recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, mapMinZoom, previousZoomLevel, newZoomLevel) {
  1365. this._recursively(bounds, newZoomLevel, mapMinZoom,
  1366. function (c) {
  1367. c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel);
  1368. //TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be.
  1369. //As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate
  1370. if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) {
  1371. c.clusterShow();
  1372. c._recursivelyRemoveChildrenFromMap(bounds, mapMinZoom, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds
  1373. } else {
  1374. c.clusterHide();
  1375. }
  1376. c._addToMap();
  1377. }
  1378. );
  1379. },
  1380. _recursivelyBecomeVisible: function (bounds, zoomLevel) {
  1381. this._recursively(bounds, this._group._map.getMinZoom(), zoomLevel, null, function (c) {
  1382. c.clusterShow();
  1383. });
  1384. },
  1385. _recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) {
  1386. this._recursively(bounds, this._group._map.getMinZoom() - 1, zoomLevel,
  1387. function (c) {
  1388. if (zoomLevel === c._zoom) {
  1389. return;
  1390. }
  1391. //Add our child markers at startPos (so they can be animated out)
  1392. for (var i = c._markers.length - 1; i >= 0; i--) {
  1393. var nm = c._markers[i];
  1394. if (!bounds.contains(nm._latlng)) {
  1395. continue;
  1396. }
  1397. if (startPos) {
  1398. nm._backupLatlng = nm.getLatLng();
  1399. nm.setLatLng(startPos);
  1400. if (nm.clusterHide) {
  1401. nm.clusterHide();
  1402. }
  1403. }
  1404. c._group._featureGroup.addLayer(nm);
  1405. }
  1406. },
  1407. function (c) {
  1408. c._addToMap(startPos);
  1409. }
  1410. );
  1411. },
  1412. _recursivelyRestoreChildPositions: function (zoomLevel) {
  1413. //Fix positions of child markers
  1414. for (var i = this._markers.length - 1; i >= 0; i--) {
  1415. var nm = this._markers[i];
  1416. if (nm._backupLatlng) {
  1417. nm.setLatLng(nm._backupLatlng);
  1418. delete nm._backupLatlng;
  1419. }
  1420. }
  1421. if (zoomLevel - 1 === this._zoom) {
  1422. //Reposition child clusters
  1423. for (var j = this._childClusters.length - 1; j >= 0; j--) {
  1424. this._childClusters[j]._restorePosition();
  1425. }
  1426. } else {
  1427. for (var k = this._childClusters.length - 1; k >= 0; k--) {
  1428. this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel);
  1429. }
  1430. }
  1431. },
  1432. _restorePosition: function () {
  1433. if (this._backupLatlng) {
  1434. this.setLatLng(this._backupLatlng);
  1435. delete this._backupLatlng;
  1436. }
  1437. },
  1438. //exceptBounds: If set, don't remove any markers/clusters in it
  1439. _recursivelyRemoveChildrenFromMap: function (previousBounds, mapMinZoom, zoomLevel, exceptBounds) {
  1440. var m, i;
  1441. this._recursively(previousBounds, mapMinZoom - 1, zoomLevel - 1,
  1442. function (c) {
  1443. //Remove markers at every level
  1444. for (i = c._markers.length - 1; i >= 0; i--) {
  1445. m = c._markers[i];
  1446. if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
  1447. c._group._featureGroup.removeLayer(m);
  1448. if (m.clusterShow) {
  1449. m.clusterShow();
  1450. }
  1451. }
  1452. }
  1453. },
  1454. function (c) {
  1455. //Remove child clusters at just the bottom level
  1456. for (i = c._childClusters.length - 1; i >= 0; i--) {
  1457. m = c._childClusters[i];
  1458. if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
  1459. c._group._featureGroup.removeLayer(m);
  1460. if (m.clusterShow) {
  1461. m.clusterShow();
  1462. }
  1463. }
  1464. }
  1465. }
  1466. );
  1467. },
  1468. //Run the given functions recursively to this and child clusters
  1469. // boundsToApplyTo: a BM.LatLngBounds representing the bounds of what clusters to recurse in to
  1470. // zoomLevelToStart: zoom level to start running functions (inclusive)
  1471. // zoomLevelToStop: zoom level to stop running functions (inclusive)
  1472. // runAtEveryLevel: function that takes an BM.MarkerCluster as an argument that should be applied on every level
  1473. // runAtBottomLevel: function that takes an BM.MarkerCluster as an argument that should be applied at only the bottom level
  1474. _recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) {
  1475. var childClusters = this._childClusters,
  1476. zoom = this._zoom,
  1477. i, c;
  1478. if (zoomLevelToStart <= zoom) {
  1479. if (runAtEveryLevel) {
  1480. runAtEveryLevel(this);
  1481. }
  1482. if (runAtBottomLevel && zoom === zoomLevelToStop) {
  1483. runAtBottomLevel(this);
  1484. }
  1485. }
  1486. if (zoom < zoomLevelToStart || zoom < zoomLevelToStop) {
  1487. for (i = childClusters.length - 1; i >= 0; i--) {
  1488. c = childClusters[i];
  1489. if (c._boundsNeedUpdate) {
  1490. c._recalculateBounds();
  1491. }
  1492. if (boundsToApplyTo.intersects(c._bounds)) {
  1493. c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
  1494. }
  1495. }
  1496. }
  1497. },
  1498. //Returns true if we are the parent of only one cluster and that cluster is the same as us
  1499. _isSingleParent: function () {
  1500. //Don't need to check this._markers as the rest won't work if there are any
  1501. return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount;
  1502. }
  1503. });
  1504. /*
  1505. * Extends BM.Marker to include two extra methods: clusterHide and clusterShow.
  1506. *
  1507. * They work as setOpacity(0) and setOpacity(1) respectively, but
  1508. * don't overwrite the options.opacity
  1509. *
  1510. */
  1511. BM.Marker.include({
  1512. clusterHide: function () {
  1513. var backup = this.options.opacity;
  1514. this.setOpacity(0);
  1515. this.options.opacity = backup;
  1516. return this;
  1517. },
  1518. clusterShow: function () {
  1519. return this.setOpacity(this.options.opacity);
  1520. }
  1521. });
  1522. BM.DistanceGrid = function (cellSize) {
  1523. this._cellSize = cellSize;
  1524. this._sqCellSize = cellSize * cellSize;
  1525. this._grid = {};
  1526. this._objectPoint = {};
  1527. };
  1528. BM.DistanceGrid.prototype = {
  1529. addObject: function (obj, point) {
  1530. var x = this._getCoord(point.x),
  1531. y = this._getCoord(point.y),
  1532. grid = this._grid,
  1533. row = grid[y] = grid[y] || {},
  1534. cell = row[x] = row[x] || [],
  1535. stamp = BM.Util.stamp(obj);
  1536. this._objectPoint[stamp] = point;
  1537. cell.push(obj);
  1538. },
  1539. updateObject: function (obj, point) {
  1540. this.removeObject(obj);
  1541. this.addObject(obj, point);
  1542. },
  1543. //Returns true if the object was found
  1544. removeObject: function (obj, point) {
  1545. var x = this._getCoord(point.x),
  1546. y = this._getCoord(point.y),
  1547. grid = this._grid,
  1548. row = grid[y] = grid[y] || {},
  1549. cell = row[x] = row[x] || [],
  1550. i, len;
  1551. delete this._objectPoint[BM.Util.stamp(obj)];
  1552. for (i = 0, len = cell.length; i < len; i++) {
  1553. if (cell[i] === obj) {
  1554. cell.splice(i, 1);
  1555. if (len === 1) {
  1556. delete row[x];
  1557. }
  1558. return true;
  1559. }
  1560. }
  1561. },
  1562. eachObject: function (fn, context) {
  1563. var i, j, k, len, row, cell, removed,
  1564. grid = this._grid;
  1565. for (i in grid) {
  1566. row = grid[i];
  1567. for (j in row) {
  1568. cell = row[j];
  1569. for (k = 0, len = cell.length; k < len; k++) {
  1570. removed = fn.call(context, cell[k]);
  1571. if (removed) {
  1572. k--;
  1573. len--;
  1574. }
  1575. }
  1576. }
  1577. }
  1578. },
  1579. getNearObject: function (point) {
  1580. var x = this._getCoord(point.x),
  1581. y = this._getCoord(point.y),
  1582. i, j, k, row, cell, len, obj, dist,
  1583. objectPoint = this._objectPoint,
  1584. closestDistSq = this._sqCellSize,
  1585. closest = null;
  1586. for (i = y - 1; i <= y + 1; i++) {
  1587. row = this._grid[i];
  1588. if (row) {
  1589. for (j = x - 1; j <= x + 1; j++) {
  1590. cell = row[j];
  1591. if (cell) {
  1592. for (k = 0, len = cell.length; k < len; k++) {
  1593. obj = cell[k];
  1594. dist = this._sqDist(objectPoint[BM.Util.stamp(obj)], point);
  1595. if (dist < closestDistSq ||
  1596. dist <= closestDistSq && closest === null) {
  1597. closestDistSq = dist;
  1598. closest = obj;
  1599. }
  1600. }
  1601. }
  1602. }
  1603. }
  1604. }
  1605. return closest;
  1606. },
  1607. _getCoord: function (x) {
  1608. var coord = Math.floor(x / this._cellSize);
  1609. return isFinite(coord) ? coord : x;
  1610. },
  1611. _sqDist: function (p, p2) {
  1612. var dx = p2.x - p.x,
  1613. dy = p2.y - p.y;
  1614. return dx * dx + dy * dy;
  1615. }
  1616. };
  1617. /* Copyright (c) 2012 the authors listed at the following URL, and/or
  1618. the authors of referenced articles or incorporated external code:
  1619. http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256
  1620. Permission is hereby granted, free of charge, to any person obtaining
  1621. a copy of this software and associated documentation files (the
  1622. "Software"), to deal in the Software without restriction, including
  1623. without limitation the rights to use, copy, modify, merge, publish,
  1624. distribute, sublicense, and/or sell copies of the Software, and to
  1625. permit persons to whom the Software is furnished to do so, subject to
  1626. the following conditions:
  1627. The above copyright notice and this permission notice shall be
  1628. included in all copies or substantial portions of the Software.
  1629. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  1630. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1631. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  1632. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  1633. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  1634. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  1635. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1636. Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434
  1637. */
  1638. (function () {
  1639. BM.QuickHull = {
  1640. /*
  1641. * @param {Object} cpt a point to be measured from the baseline
  1642. * @param {Array} bl the baseline, as represented by a two-element
  1643. * array of latlng objects.
  1644. * @returns {Number} an approximate distance measure
  1645. */
  1646. getDistant: function (cpt, bl) {
  1647. var vY = bl[1].lat - bl[0].lat,
  1648. vX = bl[0].lng - bl[1].lng;
  1649. return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng));
  1650. },
  1651. /*
  1652. * @param {Array} baseLine a two-element array of latlng objects
  1653. * representing the baseline to project from
  1654. * @param {Array} latLngs an array of latlng objects
  1655. * @returns {Object} the maximum point and all new points to stay
  1656. * in consideration for the hull.
  1657. */
  1658. findMostDistantPointFromBaseLine: function (baseLine, latLngs) {
  1659. var maxD = 0,
  1660. maxPt = null,
  1661. newPoints = [],
  1662. i, pt, d;
  1663. for (i = latLngs.length - 1; i >= 0; i--) {
  1664. pt = latLngs[i];
  1665. d = this.getDistant(pt, baseLine);
  1666. if (d > 0) {
  1667. newPoints.push(pt);
  1668. } else {
  1669. continue;
  1670. }
  1671. if (d > maxD) {
  1672. maxD = d;
  1673. maxPt = pt;
  1674. }
  1675. }
  1676. return {
  1677. maxPoint: maxPt,
  1678. newPoints: newPoints
  1679. };
  1680. },
  1681. /*
  1682. * Given a baseline, compute the convex hull of latLngs as an array
  1683. * of latLngs.
  1684. *
  1685. * @param {Array} latLngs
  1686. * @returns {Array}
  1687. */
  1688. buildConvexHull: function (baseLine, latLngs) {
  1689. var convexHullBaseLines = [],
  1690. t = this.findMostDistantPointFromBaseLine(baseLine, latLngs);
  1691. if (t.maxPoint) { // if there is still a point "outside" the base line
  1692. convexHullBaseLines =
  1693. convexHullBaseLines.concat(
  1694. this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints)
  1695. );
  1696. convexHullBaseLines =
  1697. convexHullBaseLines.concat(
  1698. this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints)
  1699. );
  1700. return convexHullBaseLines;
  1701. } else { // if there is no more point "outside" the base line, the current base line is part of the convex hull
  1702. return [baseLine[0]];
  1703. }
  1704. },
  1705. /*
  1706. * Given an array of latlngs, compute a convex hull as an array
  1707. * of latlngs
  1708. *
  1709. * @param {Array} latLngs
  1710. * @returns {Array}
  1711. */
  1712. getConvexHull: function (latLngs) {
  1713. // find first baseline
  1714. var maxLat = false,
  1715. minLat = false,
  1716. maxLng = false,
  1717. minLng = false,
  1718. maxLatPt = null,
  1719. minLatPt = null,
  1720. maxLngPt = null,
  1721. minLngPt = null,
  1722. maxPt = null,
  1723. minPt = null,
  1724. i;
  1725. for (i = latLngs.length - 1; i >= 0; i--) {
  1726. var pt = latLngs[i];
  1727. if (maxLat === false || pt.lat > maxLat) {
  1728. maxLatPt = pt;
  1729. maxLat = pt.lat;
  1730. }
  1731. if (minLat === false || pt.lat < minLat) {
  1732. minLatPt = pt;
  1733. minLat = pt.lat;
  1734. }
  1735. if (maxLng === false || pt.lng > maxLng) {
  1736. maxLngPt = pt;
  1737. maxLng = pt.lng;
  1738. }
  1739. if (minLng === false || pt.lng < minLng) {
  1740. minLngPt = pt;
  1741. minLng = pt.lng;
  1742. }
  1743. }
  1744. if (minLat !== maxLat) {
  1745. minPt = minLatPt;
  1746. maxPt = maxLatPt;
  1747. } else {
  1748. minPt = minLngPt;
  1749. maxPt = maxLngPt;
  1750. }
  1751. var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs),
  1752. this.buildConvexHull([maxPt, minPt], latLngs));
  1753. return ch;
  1754. }
  1755. };
  1756. }());
  1757. BM.MarkerCluster.include({
  1758. getConvexHull: function () {
  1759. var childMarkers = this.getAllChildMarkers(),
  1760. points = [],
  1761. p, i;
  1762. for (i = childMarkers.length - 1; i >= 0; i--) {
  1763. p = childMarkers[i].getLatLng();
  1764. points.push(p);
  1765. }
  1766. return BM.QuickHull.getConvexHull(points);
  1767. }
  1768. });
  1769. //This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-bigemap
  1770. //Huge thanks to jawj for implementing it first to make my job easy :-)
  1771. BM.MarkerCluster.include({
  1772. _2PI: Math.PI * 2,
  1773. _circleFootSeparation: 25, //related to circumference of circle
  1774. _circleStartAngle: 0,
  1775. _spiralFootSeparation: 28, //related to size of spiral (experiment!)
  1776. _spiralLengthStart: 11,
  1777. _spiralLengthFactor: 5,
  1778. _circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards.
  1779. // 0 -> always spiral; Infinity -> always circle
  1780. spiderfy: function () {
  1781. if (this._group._spiderfied === this || this._group._inZoomAnimation) {
  1782. return;
  1783. }
  1784. var childMarkers = this.getAllChildMarkers(null, true),
  1785. group = this._group,
  1786. map = group._map,
  1787. center = map.latLngToLayerPoint(this._latlng),
  1788. positions;
  1789. this._group._unspiderfy();
  1790. this._group._spiderfied = this;
  1791. //TODO Maybe: childMarkers order by distance to center
  1792. if (childMarkers.length >= this._circleSpiralSwitchover) {
  1793. positions = this._generatePointsSpiral(childMarkers.length, center);
  1794. } else {
  1795. center.y += 10; // Otherwise circles look wrong => hack for standard blue icon, renders differently for other icons.
  1796. positions = this._generatePointsCircle(childMarkers.length, center);
  1797. }
  1798. this._animationSpiderfy(childMarkers, positions);
  1799. },
  1800. unspiderfy: function (zoomDetails) {
  1801. /// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param>
  1802. if (this._group._inZoomAnimation) {
  1803. return;
  1804. }
  1805. this._animationUnspiderfy(zoomDetails);
  1806. this._group._spiderfied = null;
  1807. },
  1808. _generatePointsCircle: function (count, centerPt) {
  1809. var circumference = this._group.options.spiderfyDistanceMultiplier * this._circleFootSeparation * (2 + count),
  1810. legLength = circumference / this._2PI, //radius from circumference
  1811. angleStep = this._2PI / count,
  1812. res = [],
  1813. i, angle;
  1814. legLength = Math.max(legLength, 35); // Minimum distance to get outside the cluster icon.
  1815. res.length = count;
  1816. for (i = 0; i < count; i++) { // Clockwise, like spiral.
  1817. angle = this._circleStartAngle + i * angleStep;
  1818. res[i] = new BM.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
  1819. }
  1820. return res;
  1821. },
  1822. _generatePointsSpiral: function (count, centerPt) {
  1823. var spiderfyDistanceMultiplier = this._group.options.spiderfyDistanceMultiplier,
  1824. legLength = spiderfyDistanceMultiplier * this._spiralLengthStart,
  1825. separation = spiderfyDistanceMultiplier * this._spiralFootSeparation,
  1826. lengthFactor = spiderfyDistanceMultiplier * this._spiralLengthFactor * this._2PI,
  1827. angle = 0,
  1828. res = [],
  1829. i;
  1830. res.length = count;
  1831. // Higher index, closer position to cluster center.
  1832. for (i = count; i >= 0; i--) {
  1833. // Skip the first position, so that we are already farther from center and we avoid
  1834. // being under the default cluster icon (especially important for Circle Markers).
  1835. if (i < count) {
  1836. res[i] = new BM.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
  1837. }
  1838. angle += separation / legLength + i * 0.0005;
  1839. legLength += lengthFactor / angle;
  1840. }
  1841. return res;
  1842. },
  1843. _noanimationUnspiderfy: function () {
  1844. var group = this._group,
  1845. map = group._map,
  1846. fg = group._featureGroup,
  1847. childMarkers = this.getAllChildMarkers(null, true),
  1848. m, i;
  1849. group._ignoreMove = true;
  1850. this.setOpacity(1);
  1851. for (i = childMarkers.length - 1; i >= 0; i--) {
  1852. m = childMarkers[i];
  1853. fg.removeLayer(m);
  1854. if (m._preSpiderfyLatlng) {
  1855. m.setLatLng(m._preSpiderfyLatlng);
  1856. delete m._preSpiderfyLatlng;
  1857. }
  1858. if (m.setZIndexOffset) {
  1859. m.setZIndexOffset(0);
  1860. }
  1861. if (m._spiderLeg) {
  1862. map.removeLayer(m._spiderLeg);
  1863. delete m._spiderLeg;
  1864. }
  1865. }
  1866. group.fire('unspiderfied', {
  1867. cluster: this,
  1868. markers: childMarkers
  1869. });
  1870. group._ignoreMove = false;
  1871. group._spiderfied = null;
  1872. }
  1873. });
  1874. //Non Animated versions of everything
  1875. BM.MarkerClusterNonAnimated = BM.MarkerCluster.extend({
  1876. _animationSpiderfy: function (childMarkers, positions) {
  1877. var group = this._group,
  1878. map = group._map,
  1879. fg = group._featureGroup,
  1880. legOptions = this._group.options.spiderLegPolylineOptions,
  1881. i, m, leg, newPos;
  1882. group._ignoreMove = true;
  1883. // Traverse in ascending order to make sure that inner circleMarkers are on top of further legs. Normal markers are re-ordered by newPosition.
  1884. // The reverse order trick no longer improves performance on modern browsers.
  1885. for (i = 0; i < childMarkers.length; i++) {
  1886. newPos = map.layerPointToLatLng(positions[i]);
  1887. m = childMarkers[i];
  1888. // Add the leg before the marker, so that in case the latter is a circleMarker, the leg is behind it.
  1889. leg = new BM.Polyline([this._latlng, newPos], legOptions);
  1890. map.addLayer(leg);
  1891. m._spiderLeg = leg;
  1892. // Now add the marker.
  1893. m._preSpiderfyLatlng = m._latlng;
  1894. m.setLatLng(newPos);
  1895. if (m.setZIndexOffset) {
  1896. m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
  1897. }
  1898. fg.addLayer(m);
  1899. }
  1900. this.setOpacity(0.3);
  1901. group._ignoreMove = false;
  1902. group.fire('spiderfied', {
  1903. cluster: this,
  1904. markers: childMarkers
  1905. });
  1906. },
  1907. _animationUnspiderfy: function () {
  1908. this._noanimationUnspiderfy();
  1909. }
  1910. });
  1911. //Animated versions here
  1912. BM.MarkerCluster.include({
  1913. _animationSpiderfy: function (childMarkers, positions) {
  1914. var me = this,
  1915. group = this._group,
  1916. map = group._map,
  1917. fg = group._featureGroup,
  1918. thisLayerLatLng = this._latlng,
  1919. thisLayerPos = map.latLngToLayerPoint(thisLayerLatLng),
  1920. svg = BM.Path.SVG,
  1921. legOptions = BM.extend({}, this._group.options.spiderLegPolylineOptions), // Copy the options so that we can modify them for animation.
  1922. finalLegOpacity = legOptions.opacity,
  1923. i, m, leg, legPath, legLength, newPos;
  1924. if (finalLegOpacity === undefined) {
  1925. finalLegOpacity = BM.MarkerClusterGroup.prototype.options.spiderLegPolylineOptions.opacity;
  1926. }
  1927. if (svg) {
  1928. // If the initial opacity of the spider leg is not 0 then it appears before the animation starts.
  1929. legOptions.opacity = 0;
  1930. // Add the class for CSS transitions.
  1931. legOptions.className = (legOptions.className || '') + ' bigemap-cluster-spider-leg';
  1932. } else {
  1933. // Make sure we have a defined opacity.
  1934. legOptions.opacity = finalLegOpacity;
  1935. }
  1936. group._ignoreMove = true;
  1937. // Add markers and spider legs to map, hidden at our center point.
  1938. // Traverse in ascending order to make sure that inner circleMarkers are on top of further legs. Normal markers are re-ordered by newPosition.
  1939. // The reverse order trick no longer improves performance on modern browsers.
  1940. for (i = 0; i < childMarkers.length; i++) {
  1941. m = childMarkers[i];
  1942. newPos = map.layerPointToLatLng(positions[i]);
  1943. // Add the leg before the marker, so that in case the latter is a circleMarker, the leg is behind it.
  1944. leg = new BM.Polyline([thisLayerLatLng, newPos], legOptions);
  1945. map.addLayer(leg);
  1946. m._spiderLeg = leg;
  1947. // Explanations: https://jakearchibald.com/2013/animated-line-drawing-svg/
  1948. // In our case the transition property is declared in the CSS file.
  1949. if (svg) {
  1950. legPath = leg._path;
  1951. legLength = legPath.getTotalLength() + 0.1; // Need a small extra length to avoid remaining dot in Firefox.
  1952. legPath.style.strokeDasharray = legLength; // Just 1 length is enough, it will be duplicated.
  1953. legPath.style.strokeDashoffset = legLength;
  1954. }
  1955. // If it is a marker, add it now and we'll animate it out
  1956. if (m.setZIndexOffset) {
  1957. m.setZIndexOffset(1000000); // Make normal markers appear on top of EVERYTHING
  1958. }
  1959. if (m.clusterHide) {
  1960. m.clusterHide();
  1961. }
  1962. // Vectors just get immediately added
  1963. fg.addLayer(m);
  1964. if (m._setPos) {
  1965. m._setPos(thisLayerPos);
  1966. }
  1967. }
  1968. group._forceLayout();
  1969. group._animationStart();
  1970. // Reveal markers and spider legs.
  1971. for (i = childMarkers.length - 1; i >= 0; i--) {
  1972. newPos = map.layerPointToLatLng(positions[i]);
  1973. m = childMarkers[i];
  1974. //Move marker to new position
  1975. m._preSpiderfyLatlng = m._latlng;
  1976. m.setLatLng(newPos);
  1977. if (m.clusterShow) {
  1978. m.clusterShow();
  1979. }
  1980. // Animate leg (animation is actually delegated to CSS transition).
  1981. if (svg) {
  1982. leg = m._spiderLeg;
  1983. legPath = leg._path;
  1984. legPath.style.strokeDashoffset = 0;
  1985. //legPath.style.strokeOpacity = finalLegOpacity;
  1986. leg.setStyle({
  1987. opacity: finalLegOpacity
  1988. });
  1989. }
  1990. }
  1991. this.setOpacity(0.3);
  1992. group._ignoreMove = false;
  1993. setTimeout(function () {
  1994. group._animationEnd();
  1995. group.fire('spiderfied', {
  1996. cluster: me,
  1997. markers: childMarkers
  1998. });
  1999. }, 200);
  2000. },
  2001. _animationUnspiderfy: function (zoomDetails) {
  2002. var me = this,
  2003. group = this._group,
  2004. map = group._map,
  2005. fg = group._featureGroup,
  2006. thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng),
  2007. childMarkers = this.getAllChildMarkers(null, true),
  2008. svg = BM.Path.SVG,
  2009. m, i, leg, legPath, legLength, nonAnimatable;
  2010. group._ignoreMove = true;
  2011. group._animationStart();
  2012. //Make us visible and bring the child markers back in
  2013. this.setOpacity(1);
  2014. for (i = childMarkers.length - 1; i >= 0; i--) {
  2015. m = childMarkers[i];
  2016. //Marker was added to us after we were spiderfied
  2017. if (!m._preSpiderfyLatlng) {
  2018. continue;
  2019. }
  2020. //Close any popup on the marker first, otherwise setting the location of the marker will make the map scroll
  2021. m.closePopup();
  2022. //Fix up the location to the real one
  2023. m.setLatLng(m._preSpiderfyLatlng);
  2024. delete m._preSpiderfyLatlng;
  2025. //Hack override the location to be our center
  2026. nonAnimatable = true;
  2027. if (m._setPos) {
  2028. m._setPos(thisLayerPos);
  2029. nonAnimatable = false;
  2030. }
  2031. if (m.clusterHide) {
  2032. m.clusterHide();
  2033. nonAnimatable = false;
  2034. }
  2035. if (nonAnimatable) {
  2036. fg.removeLayer(m);
  2037. }
  2038. // Animate the spider leg back in (animation is actually delegated to CSS transition).
  2039. if (svg) {
  2040. leg = m._spiderLeg;
  2041. legPath = leg._path;
  2042. legLength = legPath.getTotalLength() + 0.1;
  2043. legPath.style.strokeDashoffset = legLength;
  2044. leg.setStyle({
  2045. opacity: 0
  2046. });
  2047. }
  2048. }
  2049. group._ignoreMove = false;
  2050. setTimeout(function () {
  2051. //If we have only <= one child left then that marker will be shown on the map so don't remove it!
  2052. var stillThereChildCount = 0;
  2053. for (i = childMarkers.length - 1; i >= 0; i--) {
  2054. m = childMarkers[i];
  2055. if (m._spiderLeg) {
  2056. stillThereChildCount++;
  2057. }
  2058. }
  2059. for (i = childMarkers.length - 1; i >= 0; i--) {
  2060. m = childMarkers[i];
  2061. if (!m._spiderLeg) { //Has already been unspiderfied
  2062. continue;
  2063. }
  2064. if (m.clusterShow) {
  2065. m.clusterShow();
  2066. }
  2067. if (m.setZIndexOffset) {
  2068. m.setZIndexOffset(0);
  2069. }
  2070. if (stillThereChildCount > 1) {
  2071. fg.removeLayer(m);
  2072. }
  2073. map.removeLayer(m._spiderLeg);
  2074. delete m._spiderLeg;
  2075. }
  2076. group._animationEnd();
  2077. group.fire('unspiderfied', {
  2078. cluster: me,
  2079. markers: childMarkers
  2080. });
  2081. }, 200);
  2082. }
  2083. });
  2084. BM.MarkerClusterGroup.include({
  2085. //The MarkerCluster currently spiderfied (if any)
  2086. _spiderfied: null,
  2087. unspiderfy: function () {
  2088. this._unspiderfy.apply(this, arguments);
  2089. },
  2090. _spiderfierOnAdd: function () {
  2091. this._map.on('click', this._unspiderfyWrapper, this);
  2092. if (this._map.options.zoomAnimation) {
  2093. this._map.on('zoomstart', this._unspiderfyZoomStart, this);
  2094. }
  2095. //Browsers without zoomAnimation or a big zoom don't fire zoomstart
  2096. this._map.on('zoomend', this._noanimationUnspiderfy, this);
  2097. if (!BM.Browser.touch) {
  2098. this._map.getRenderer(this);
  2099. //Needs to happen in the pageload, not after, or animations don't work in webkit
  2100. // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements
  2101. //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable
  2102. }
  2103. },
  2104. _spiderfierOnRemove: function () {
  2105. this._map.off('click', this._unspiderfyWrapper, this);
  2106. this._map.off('zoomstart', this._unspiderfyZoomStart, this);
  2107. this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
  2108. this._map.off('zoomend', this._noanimationUnspiderfy, this);
  2109. //Ensure that markers are back where they should be
  2110. // Use no animation to avoid a sticky bigemap-cluster-anim class on mapPane
  2111. this._noanimationUnspiderfy();
  2112. },
  2113. //On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated)
  2114. //This means we can define the animation they do rather than Markers doing an animation to their actual location
  2115. _unspiderfyZoomStart: function () {
  2116. if (!this._map) { //May have been removed from the map by a zoomEnd handler
  2117. return;
  2118. }
  2119. this._map.on('zoomanim', this._unspiderfyZoomAnim, this);
  2120. },
  2121. _unspiderfyZoomAnim: function (zoomDetails) {
  2122. //Wait until the first zoomanim after the user has finished touch-zooming before running the animation
  2123. if (BM.DomUtil.hasClass(this._map._mapPane, 'bigemap-touching')) {
  2124. return;
  2125. }
  2126. this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
  2127. this._unspiderfy(zoomDetails);
  2128. },
  2129. _unspiderfyWrapper: function () {
  2130. /// <summary>_unspiderfy but passes no arguments</summary>
  2131. this._unspiderfy();
  2132. },
  2133. _unspiderfy: function (zoomDetails) {
  2134. if (this._spiderfied) {
  2135. this._spiderfied.unspiderfy(zoomDetails);
  2136. }
  2137. },
  2138. _noanimationUnspiderfy: function () {
  2139. if (this._spiderfied) {
  2140. this._spiderfied._noanimationUnspiderfy();
  2141. }
  2142. },
  2143. //If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
  2144. _unspiderfyLayer: function (layer) {
  2145. if (layer._spiderLeg) {
  2146. this._featureGroup.removeLayer(layer);
  2147. if (layer.clusterShow) {
  2148. layer.clusterShow();
  2149. }
  2150. //Position will be fixed up immediately in _animationUnspiderfy
  2151. if (layer.setZIndexOffset) {
  2152. layer.setZIndexOffset(0);
  2153. }
  2154. this._map.removeLayer(layer._spiderLeg);
  2155. delete layer._spiderLeg;
  2156. }
  2157. }
  2158. });
  2159. /**
  2160. * Adds 1 public method to MCG and 1 to BM.Marker to facilitate changing
  2161. * markers' icon options and refreshing their icon and their parent clusters
  2162. * accordingly (case where their iconCreateFunction uses data of childMarkers
  2163. * to make up the cluster icon).
  2164. */
  2165. BM.MarkerClusterGroup.include({
  2166. /**
  2167. * Updates the icon of all clusters which are parents of the given marker(s).
  2168. * In singleMarkerMode, also updates the given marker(s) icon.
  2169. * @param layers BM.MarkerClusterGroup|BM.LayerGroup|Array(BM.Marker)|Map(BM.Marker)|
  2170. * BM.MarkerCluster|BM.Marker (optional) list of markers (or single marker) whose parent
  2171. * clusters need to be updated. If not provided, retrieves all child markers of this.
  2172. * @returns {BM.MarkerClusterGroup}
  2173. */
  2174. refreshClusters: function (layers) {
  2175. if (!layers) {
  2176. layers = this._topClusterLevel.getAllChildMarkers();
  2177. } else if (layers instanceof BM.MarkerClusterGroup) {
  2178. layers = layers._topClusterLevel.getAllChildMarkers();
  2179. } else if (layers instanceof BM.LayerGroup) {
  2180. layers = layers._layers;
  2181. } else if (layers instanceof BM.MarkerCluster) {
  2182. layers = layers.getAllChildMarkers();
  2183. } else if (layers instanceof BM.Marker) {
  2184. layers = [layers];
  2185. } // else: must be an Array(BM.Marker)|Map(BM.Marker)
  2186. this._flagParentsIconsNeedUpdate(layers);
  2187. this._refreshClustersIcons();
  2188. // In case of singleMarkerMode, also re-draw the markers.
  2189. if (this.options.singleMarkerMode) {
  2190. this._refreshSingleMarkerModeMarkers(layers);
  2191. }
  2192. return this;
  2193. },
  2194. /**
  2195. * Simply flags all parent clusters of the given markers as having a "dirty" icon.
  2196. * @param layers Array(BM.Marker)|Map(BM.Marker) list of markers.
  2197. * @private
  2198. */
  2199. _flagParentsIconsNeedUpdate: function (layers) {
  2200. var id, parent;
  2201. // Assumes layers is an Array or an Object whose prototype is non-enumerable.
  2202. for (id in layers) {
  2203. // Flag parent clusters' icon as "dirty", all the way up.
  2204. // Dumb process that flags multiple times upper parents, but still
  2205. // much more efficient than trying to be smart and make short lists,
  2206. // at least in the case of a hierarchy following a power law:
  2207. // http://jsperf.com/flag-nodes-in-power-hierarchy/2
  2208. parent = layers[id].__parent;
  2209. while (parent) {
  2210. parent._iconNeedsUpdate = true;
  2211. parent = parent.__parent;
  2212. }
  2213. }
  2214. },
  2215. /**
  2216. * Re-draws the icon of the supplied markers.
  2217. * To be used in singleMarkerMode only.
  2218. * @param layers Array(BM.Marker)|Map(BM.Marker) list of markers.
  2219. * @private
  2220. */
  2221. _refreshSingleMarkerModeMarkers: function (layers) {
  2222. var id, layer;
  2223. for (id in layers) {
  2224. layer = layers[id];
  2225. // Make sure we do not override markers that do not belong to THIS group.
  2226. if (this.hasLayer(layer)) {
  2227. // Need to re-create the icon first, then re-draw the marker.
  2228. layer.setIcon(this._overrideMarkerIcon(layer));
  2229. }
  2230. }
  2231. }
  2232. });
  2233. BM.Marker.include({
  2234. /**
  2235. * Updates the given options in the marker's icon and refreshes the marker.
  2236. * @param options map object of icon options.
  2237. * @param directlyRefreshClusters boolean (optional) true to trigger
  2238. * MCG.refreshClustersOf() right away with this single marker.
  2239. * @returns {BM.Marker}
  2240. */
  2241. refreshIconOptions: function (options, directlyRefreshClusters) {
  2242. var icon = this.options.icon;
  2243. BM.setOptions(icon, options);
  2244. this.setIcon(icon);
  2245. // Shortcut to refresh the associated MCG clusters right away.
  2246. // To be used when refreshing a single marker.
  2247. // Otherwise, better use MCG.refreshClusters() once at the end with
  2248. // the list of modified markers.
  2249. if (directlyRefreshClusters && this.__parent) {
  2250. this.__parent._group.refreshClusters(this);
  2251. }
  2252. return this;
  2253. }
  2254. });
  2255. exports.MarkerClusterGroup = MarkerClusterGroup;
  2256. exports.MarkerCluster = MarkerCluster;
  2257. })));
  2258. //# sourceMappingURL=bigemap.markercluster-src.js.map