leaflet.markercluster-src.js 75 KB

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