leaflet.markercluster-src.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  1. /*
  2. Copyright (c) 2012, Smartrak, David Leaver
  3. Leaflet.markercluster is an open-source JavaScript library for Marker Clustering on leaflet powered maps.
  4. https://github.com/danzel/Leaflet.markercluster
  5. */
  6. (function (window, undefined) {
  7. /*
  8. * L.MarkerClusterGroup extends L.FeatureGroup by clustering the markers contained within
  9. */
  10. L.MarkerClusterGroup = L.FeatureGroup.extend({
  11. options: {
  12. maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center
  13. iconCreateFunction: null,
  14. spiderfyOnMaxZoom: true,
  15. showCoverageOnHover: true,
  16. zoomToBoundsOnClick: true,
  17. singleMarkerMode: false,
  18. disableClusteringAtZoom: null,
  19. //Whether to animate adding markers after adding the MarkerClusterGroup to the map
  20. // If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains.
  21. animateAddingMarkers: false,
  22. //Options to pass to the L.Polygon constructor
  23. polygonOptions: {}
  24. },
  25. initialize: function (options) {
  26. L.Util.setOptions(this, options);
  27. if (!this.options.iconCreateFunction) {
  28. this.options.iconCreateFunction = this._defaultIconCreateFunction;
  29. }
  30. L.FeatureGroup.prototype.initialize.call(this, []);
  31. this._inZoomAnimation = 0;
  32. this._needsClustering = [];
  33. //The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
  34. this._currentShownBounds = null;
  35. },
  36. addLayer: function (layer) {
  37. if (layer instanceof L.LayerGroup) {
  38. var array = [];
  39. for (var i in layer._layers) {
  40. if (layer._layers.hasOwnProperty(i)) {
  41. array.push(layer._layers[i]);
  42. }
  43. }
  44. return this.addLayers(array);
  45. }
  46. if (this.options.singleMarkerMode) {
  47. layer.options.icon = this.options.iconCreateFunction({
  48. getChildCount: function () {
  49. return 1;
  50. },
  51. getAllChildMarkers: function () {
  52. return [layer];
  53. }
  54. });
  55. }
  56. if (!this._map) {
  57. this._needsClustering.push(layer);
  58. return this;
  59. }
  60. if (this.hasLayer(layer)) {
  61. return this;
  62. }
  63. //If we have already clustered we'll need to add this one to a cluster
  64. if (this._unspiderfy) {
  65. this._unspiderfy();
  66. }
  67. this._addLayer(layer, this._maxZoom);
  68. //Work out what is visible
  69. var visibleLayer = layer,
  70. currentZoom = this._map.getZoom();
  71. if (layer.__parent) {
  72. while (visibleLayer.__parent._zoom >= currentZoom) {
  73. visibleLayer = visibleLayer.__parent;
  74. }
  75. }
  76. if (this._currentShownBounds.contains(visibleLayer.getLatLng())) {
  77. if (this.options.animateAddingMarkers) {
  78. this._animationAddLayer(layer, visibleLayer);
  79. } else {
  80. this._animationAddLayerNonAnimated(layer, visibleLayer);
  81. }
  82. }
  83. return this;
  84. },
  85. removeLayer: function (layer) {
  86. if (!this._map) {
  87. this._arraySplice(this._needsClustering, layer);
  88. return this;
  89. }
  90. if (!layer.__parent) {
  91. return this;
  92. }
  93. if (this._unspiderfy) {
  94. this._unspiderfy();
  95. this._unspiderfyLayer(layer);
  96. }
  97. //Remove the marker from clusters
  98. this._removeLayer(layer, true);
  99. if (layer._icon) {
  100. L.FeatureGroup.prototype.removeLayer.call(this, layer);
  101. layer.setOpacity(1);
  102. }
  103. return this;
  104. },
  105. //Takes an array of markers and adds them in bulk
  106. addLayers: function (layersArray) {
  107. if (!this._map) {
  108. this._needsClustering = this._needsClustering.concat(layersArray);
  109. return this;
  110. }
  111. for (var i = 0, l = layersArray.length; i < l; i++) {
  112. var m = layersArray[i];
  113. this._addLayer(m, this._maxZoom);
  114. //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
  115. if (m.__parent) {
  116. if (m.__parent.getChildCount() === 2) {
  117. var markers = m.__parent.getAllChildMarkers(),
  118. otherMarker = markers[0] === m ? markers[1] : markers[0];
  119. L.FeatureGroup.prototype.removeLayer.call(this, otherMarker);
  120. }
  121. }
  122. }
  123. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
  124. return this;
  125. },
  126. //Takes an array of markers and removes them in bulk
  127. removeLayers: function (layersArray) {
  128. var i, l, m;
  129. if (!this._map) {
  130. for (i = 0, l = layersArray.length; i < l; i++) {
  131. this._arraySplice(this._needsClustering, layersArray[i]);
  132. }
  133. return this;
  134. }
  135. for (i = 0, l = layersArray.length; i < l; i++) {
  136. m = layersArray[i];
  137. this._removeLayer(m, true, true);
  138. if (m._icon) {
  139. L.FeatureGroup.prototype.removeLayer.call(this, m);
  140. m.setOpacity(1);
  141. }
  142. }
  143. //Fix up the clusters and markers on the map
  144. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
  145. for (i in this._layers) {
  146. if (this._layers.hasOwnProperty(i)) {
  147. m = this._layers[i];
  148. if (m instanceof L.MarkerCluster) {
  149. m._updateIcon();
  150. }
  151. }
  152. }
  153. return this;
  154. },
  155. //Removes all layers from the MarkerClusterGroup
  156. clearLayers: function () {
  157. //Need our own special implementation as the LayerGroup one doesn't work for us
  158. //If we aren't on the map yet, just blow away the markers we know of
  159. if (!this._map) {
  160. this._needsClustering = [];
  161. return this;
  162. }
  163. if (this._unspiderfy) {
  164. this._unspiderfy();
  165. }
  166. //Remove all the visible layers
  167. for (var i in this._layers) {
  168. if (this._layers.hasOwnProperty(i)) {
  169. L.FeatureGroup.prototype.removeLayer.call(this, this._layers[i]);
  170. }
  171. }
  172. //Reset _topClusterLevel and the DistanceGrids
  173. this._generateInitialClusters();
  174. return this;
  175. },
  176. //Returns true if the given layer is in this MarkerClusterGroup
  177. hasLayer: function (layer) {
  178. if (this._needsClustering.length > 0) {
  179. var anArray = this._needsClustering;
  180. for (var i = anArray.length - 1; i >= 0; i--) {
  181. if (anArray[i] === layer) {
  182. return true;
  183. }
  184. }
  185. }
  186. return !!(layer.__parent && layer.__parent._group === this);
  187. },
  188. //Zoom down to show the given layer (spiderfying if necessary) then calls the callback
  189. zoomToShowLayer: function (layer, callback) {
  190. var showMarker = function () {
  191. if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) {
  192. this._map.off('moveend', showMarker, this);
  193. this.off('animationend', showMarker, this);
  194. if (layer._icon) {
  195. callback();
  196. } else if (layer.__parent._icon) {
  197. var afterSpiderfy = function () {
  198. this.off('spiderfied', afterSpiderfy, this);
  199. callback();
  200. };
  201. this.on('spiderfied', afterSpiderfy, this);
  202. layer.__parent.spiderfy();
  203. }
  204. }
  205. };
  206. if (layer._icon) {
  207. callback();
  208. } else if (layer.__parent._zoom < this._map.getZoom()) {
  209. //Layer should be visible now but isn't on screen, just pan over to it
  210. this._map.on('moveend', showMarker, this);
  211. if (!layer._icon) {
  212. this._map.panTo(layer.getLatLng());
  213. }
  214. } else {
  215. this._map.on('moveend', showMarker, this);
  216. this.on('animationend', showMarker, this);
  217. this._map.setView(layer.getLatLng(), layer.__parent._zoom + 1);
  218. layer.__parent.zoomToBounds();
  219. }
  220. },
  221. //Overrides FeatureGroup.onAdd
  222. onAdd: function (map) {
  223. L.FeatureGroup.prototype.onAdd.call(this, map);
  224. if (!this._gridClusters) {
  225. this._generateInitialClusters();
  226. }
  227. for (var i = 0, l = this._needsClustering.length; i < l; i++) {
  228. this._addLayer(this._needsClustering[i], this._maxZoom);
  229. }
  230. this._needsClustering = [];
  231. this._map.on('zoomend', this._zoomEnd, this);
  232. this._map.on('moveend', this._moveEnd, this);
  233. if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
  234. this._spiderfierOnAdd();
  235. }
  236. this._bindEvents();
  237. //Actually add our markers to the map:
  238. //Remember the current zoom level and bounds
  239. this._zoom = this._map.getZoom();
  240. this._currentShownBounds = this._getExpandedVisibleBounds();
  241. //Make things appear on the map
  242. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
  243. },
  244. //Overrides FeatureGroup.onRemove
  245. onRemove: function (map) {
  246. this._map.off('zoomend', this._zoomEnd, this);
  247. this._map.off('moveend', this._moveEnd, this);
  248. //In case we are in a cluster animation
  249. this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
  250. if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
  251. this._spiderfierOnRemove();
  252. }
  253. L.FeatureGroup.prototype.onRemove.call(this, map);
  254. },
  255. //Remove the given object from the given array
  256. _arraySplice: function (anArray, obj) {
  257. for (var i = anArray.length - 1; i >= 0; i--) {
  258. if (anArray[i] === obj) {
  259. anArray.splice(i, 1);
  260. return;
  261. }
  262. }
  263. },
  264. //Internal function for removing a marker from everything.
  265. //dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions)
  266. _removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) {
  267. var gridClusters = this._gridClusters,
  268. gridUnclustered = this._gridUnclustered,
  269. map = this._map;
  270. //Remove the marker from distance clusters it might be in
  271. if (removeFromDistanceGrid) {
  272. for (var z = this._maxZoom; z >= 0; z--) {
  273. if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) {
  274. break;
  275. }
  276. }
  277. }
  278. //Work our way up the clusters removing them as we go if required
  279. var cluster = marker.__parent,
  280. markers = cluster._markers,
  281. otherMarker;
  282. //Remove the marker from the immediate parents marker list
  283. this._arraySplice(markers, marker);
  284. while (cluster) {
  285. cluster._childCount--;
  286. if (cluster._zoom < 0) {
  287. //Top level, do nothing
  288. break;
  289. } else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required
  290. //We need to push the other marker up to the parent
  291. otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0];
  292. //Update distance grid
  293. gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom));
  294. gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom));
  295. //Move otherMarker up to parent
  296. this._arraySplice(cluster.__parent._childClusters, cluster);
  297. cluster.__parent._markers.push(otherMarker);
  298. otherMarker.__parent = cluster.__parent;
  299. if (cluster._icon) {
  300. //Cluster is currently on the map, need to put the marker on the map instead
  301. L.FeatureGroup.prototype.removeLayer.call(this, cluster);
  302. if (!dontUpdateMap) {
  303. L.FeatureGroup.prototype.addLayer.call(this, otherMarker);
  304. }
  305. }
  306. } else {
  307. cluster._recalculateBounds();
  308. if (!dontUpdateMap || !cluster._icon) {
  309. cluster._updateIcon();
  310. }
  311. }
  312. cluster = cluster.__parent;
  313. }
  314. },
  315. //Overrides FeatureGroup._propagateEvent
  316. _propagateEvent: function (e) {
  317. if (e.target instanceof L.MarkerCluster) {
  318. e.type = 'cluster' + e.type;
  319. }
  320. L.FeatureGroup.prototype._propagateEvent.call(this, e);
  321. },
  322. //Default functionality
  323. _defaultIconCreateFunction: function (cluster) {
  324. var childCount = cluster.getChildCount();
  325. var c = ' marker-cluster-';
  326. if (childCount < 10) {
  327. c += 'small';
  328. } else if (childCount < 100) {
  329. c += 'medium';
  330. } else {
  331. c += 'large';
  332. }
  333. return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
  334. },
  335. _bindEvents: function () {
  336. var shownPolygon = null,
  337. map = this._map,
  338. spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
  339. showCoverageOnHover = this.options.showCoverageOnHover,
  340. zoomToBoundsOnClick = this.options.zoomToBoundsOnClick;
  341. //Zoom on cluster click or spiderfy if we are at the lowest level
  342. if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
  343. this.on('clusterclick', function (a) {
  344. if (map.getMaxZoom() === map.getZoom()) {
  345. if (spiderfyOnMaxZoom) {
  346. a.layer.spiderfy();
  347. }
  348. } else if (zoomToBoundsOnClick) {
  349. a.layer.zoomToBounds();
  350. }
  351. }, this);
  352. }
  353. //Show convex hull (boundary) polygon on mouse over
  354. if (showCoverageOnHover) {
  355. this.on('clustermouseover', function (a) {
  356. if (this._inZoomAnimation) {
  357. return;
  358. }
  359. if (shownPolygon) {
  360. map.removeLayer(shownPolygon);
  361. }
  362. if (a.layer.getChildCount() > 2) {
  363. shownPolygon = new L.Polygon(a.layer.getConvexHull(), this.options.polygonOptions);
  364. map.addLayer(shownPolygon);
  365. }
  366. }, this);
  367. this.on('clustermouseout', function () {
  368. if (shownPolygon) {
  369. map.removeLayer(shownPolygon);
  370. shownPolygon = null;
  371. }
  372. }, this);
  373. map.on('zoomend', function () {
  374. if (shownPolygon) {
  375. map.removeLayer(shownPolygon);
  376. shownPolygon = null;
  377. }
  378. }, this);
  379. map.on('layerremove', function (opt) {
  380. if (shownPolygon && opt.layer === this) {
  381. map.removeLayer(shownPolygon);
  382. shownPolygon = null;
  383. }
  384. }, this);
  385. }
  386. },
  387. _zoomEnd: function () {
  388. if (!this._map) { //May have been removed from the map by a zoomEnd handler
  389. return;
  390. }
  391. this._mergeSplitClusters();
  392. this._zoom = this._map._zoom;
  393. this._currentShownBounds = this._getExpandedVisibleBounds();
  394. },
  395. _moveEnd: function () {
  396. if (this._inZoomAnimation) {
  397. return;
  398. }
  399. var newBounds = this._getExpandedVisibleBounds();
  400. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, newBounds);
  401. this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, newBounds);
  402. this._currentShownBounds = newBounds;
  403. return;
  404. },
  405. _generateInitialClusters: function () {
  406. var maxZoom = this._map.getMaxZoom(),
  407. radius = this.options.maxClusterRadius;
  408. if (this.options.disableClusteringAtZoom) {
  409. maxZoom = this.options.disableClusteringAtZoom - 1;
  410. }
  411. this._maxZoom = maxZoom;
  412. this._gridClusters = {};
  413. this._gridUnclustered = {};
  414. //Set up DistanceGrids for each zoom
  415. for (var zoom = maxZoom; zoom >= 0; zoom--) {
  416. this._gridClusters[zoom] = new L.DistanceGrid(radius);
  417. this._gridUnclustered[zoom] = new L.DistanceGrid(radius);
  418. }
  419. this._topClusterLevel = new L.MarkerCluster(this, -1);
  420. },
  421. //Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom)
  422. _addLayer: function (layer, zoom) {
  423. var gridClusters = this._gridClusters,
  424. gridUnclustered = this._gridUnclustered,
  425. markerPoint, z;
  426. //Find the lowest zoom level to slot this one in
  427. for (; zoom >= 0; zoom--) {
  428. markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position
  429. //Try find a cluster close by
  430. var closest = gridClusters[zoom].getNearObject(markerPoint);
  431. if (closest) {
  432. closest._addChild(layer);
  433. layer.__parent = closest;
  434. return;
  435. }
  436. //Try find a marker close by to form a new cluster with
  437. closest = gridUnclustered[zoom].getNearObject(markerPoint);
  438. if (closest) {
  439. if (closest.__parent) {
  440. this._removeLayer(closest, false);
  441. }
  442. var parent = closest.__parent;
  443. //Create new cluster with these 2 in it
  444. var newCluster = new L.MarkerCluster(this, zoom, closest, layer);
  445. gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom));
  446. closest.__parent = newCluster;
  447. layer.__parent = newCluster;
  448. //First create any new intermediate parent clusters that don't exist
  449. var lastParent = newCluster;
  450. for (z = zoom - 1; z > parent._zoom; z--) {
  451. lastParent = new L.MarkerCluster(this, z, lastParent);
  452. gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z));
  453. }
  454. parent._addChild(lastParent);
  455. //Remove closest from this zoom level and any above that it is in, replace with newCluster
  456. for (z = zoom; z >= 0; z--) {
  457. if (!gridUnclustered[z].removeObject(closest, this._map.project(closest.getLatLng(), z))) {
  458. break;
  459. }
  460. }
  461. return;
  462. }
  463. //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards
  464. gridUnclustered[zoom].addObject(layer, markerPoint);
  465. }
  466. //Didn't get in anything, add us to the top
  467. this._topClusterLevel._addChild(layer);
  468. layer.__parent = this._topClusterLevel;
  469. return;
  470. },
  471. //Merge and split any existing clusters that are too big or small
  472. _mergeSplitClusters: function () {
  473. if (this._zoom < this._map._zoom) { //Zoom in, split
  474. this._animationStart();
  475. //Remove clusters now off screen
  476. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, this._getExpandedVisibleBounds());
  477. this._animationZoomIn(this._zoom, this._map._zoom);
  478. } else if (this._zoom > this._map._zoom) { //Zoom out, merge
  479. this._animationStart();
  480. this._animationZoomOut(this._zoom, this._map._zoom);
  481. } else {
  482. this._moveEnd();
  483. }
  484. },
  485. //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)
  486. _getExpandedVisibleBounds: function () {
  487. var map = this._map,
  488. bounds = map.getPixelBounds(),
  489. width = L.Browser.mobile ? 0 : Math.abs(bounds.max.x - bounds.min.x),
  490. height = L.Browser.mobile ? 0 : Math.abs(bounds.max.y - bounds.min.y),
  491. sw = map.unproject(new L.Point(bounds.min.x - width, bounds.min.y - height)),
  492. ne = map.unproject(new L.Point(bounds.max.x + width, bounds.max.y + height));
  493. return new L.LatLngBounds(sw, ne);
  494. },
  495. //Shared animation code
  496. _animationAddLayerNonAnimated: function (layer, newCluster) {
  497. if (newCluster === layer) {
  498. L.FeatureGroup.prototype.addLayer.call(this, layer);
  499. } else if (newCluster._childCount === 2) {
  500. newCluster._addToMap();
  501. var markers = newCluster.getAllChildMarkers();
  502. L.FeatureGroup.prototype.removeLayer.call(this, markers[0]);
  503. L.FeatureGroup.prototype.removeLayer.call(this, markers[1]);
  504. } else {
  505. newCluster._updateIcon();
  506. }
  507. }
  508. });
  509. L.MarkerClusterGroup.include(!L.DomUtil.TRANSITION ? {
  510. //Non Animated versions of everything
  511. _animationStart: function () {
  512. //Do nothing...
  513. },
  514. _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
  515. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
  516. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  517. },
  518. _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
  519. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
  520. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  521. },
  522. _animationAddLayer: function (layer, newCluster) {
  523. this._animationAddLayerNonAnimated(layer, newCluster);
  524. }
  525. } : {
  526. //Animated versions here
  527. _animationStart: function () {
  528. this._map._mapPane.className += ' leaflet-cluster-anim';
  529. this._inZoomAnimation++;
  530. },
  531. _animationEnd: function () {
  532. if (this._map) {
  533. this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
  534. }
  535. this._inZoomAnimation--;
  536. this.fire('animationend');
  537. },
  538. _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
  539. var me = this,
  540. bounds = this._getExpandedVisibleBounds(),
  541. i;
  542. //Add all children of current clusters to map and remove those clusters from map
  543. this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
  544. var startPos = c._latlng,
  545. markers = c._markers,
  546. m;
  547. if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us
  548. L.FeatureGroup.prototype.removeLayer.call(me, c);
  549. c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds);
  550. } else {
  551. //Fade out old cluster
  552. c.setOpacity(0);
  553. c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds);
  554. }
  555. //Remove all markers that aren't visible any more
  556. //TODO: Do we actually need to do this on the higher levels too?
  557. for (i = markers.length - 1; i >= 0; i--) {
  558. m = markers[i];
  559. if (!bounds.contains(m._latlng)) {
  560. L.FeatureGroup.prototype.removeLayer.call(me, m);
  561. }
  562. }
  563. });
  564. this._forceLayout();
  565. var j, n;
  566. //Update opacities
  567. me._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel);
  568. //TODO Maybe? Update markers in _recursivelyBecomeVisible
  569. for (j in me._layers) {
  570. if (me._layers.hasOwnProperty(j)) {
  571. n = me._layers[j];
  572. if (!(n instanceof L.MarkerCluster) && n._icon) {
  573. n.setOpacity(1);
  574. }
  575. }
  576. }
  577. //update the positions of the just added clusters/markers
  578. me._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) {
  579. c._recursivelyRestoreChildPositions(newZoomLevel);
  580. });
  581. //Remove the old clusters and close the zoom animation
  582. setTimeout(function () {
  583. //update the positions of the just added clusters/markers
  584. me._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
  585. L.FeatureGroup.prototype.removeLayer.call(me, c);
  586. c.setOpacity(1);
  587. });
  588. me._animationEnd();
  589. }, 250);
  590. },
  591. _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
  592. this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel);
  593. //Need to add markers for those that weren't on the map before but are now
  594. this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
  595. //Remove markers that were on the map before but won't be now
  596. this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel, this._getExpandedVisibleBounds());
  597. },
  598. _animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) {
  599. var bounds = this._getExpandedVisibleBounds();
  600. //Animate all of the markers in the clusters to move to their cluster center point
  601. cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, previousZoomLevel + 1, newZoomLevel);
  602. var me = this;
  603. //Update the opacity (If we immediately set it they won't animate)
  604. this._forceLayout();
  605. cluster._recursivelyBecomeVisible(bounds, newZoomLevel);
  606. //TODO: Maybe use the transition timing stuff to make this more reliable
  607. //When the animations are done, tidy up
  608. setTimeout(function () {
  609. //This cluster stopped being a cluster before the timeout fired
  610. if (cluster._childCount === 1) {
  611. var m = cluster._markers[0];
  612. //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
  613. m.setLatLng(m.getLatLng());
  614. m.setOpacity(1);
  615. return;
  616. }
  617. cluster._recursively(bounds, newZoomLevel, 0, function (c) {
  618. c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel + 1);
  619. });
  620. me._animationEnd();
  621. }, 250);
  622. },
  623. _animationAddLayer: function (layer, newCluster) {
  624. var me = this;
  625. L.FeatureGroup.prototype.addLayer.call(this, layer);
  626. if (newCluster !== layer) {
  627. if (newCluster._childCount > 2) { //Was already a cluster
  628. newCluster._updateIcon();
  629. this._forceLayout();
  630. this._animationStart();
  631. layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng()));
  632. layer.setOpacity(0);
  633. setTimeout(function () {
  634. L.FeatureGroup.prototype.removeLayer.call(me, layer);
  635. layer.setOpacity(1);
  636. me._animationEnd();
  637. }, 250);
  638. } else { //Just became a cluster
  639. this._forceLayout();
  640. me._animationStart();
  641. me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._map.getZoom());
  642. }
  643. }
  644. },
  645. //Force a browser layout of stuff in the map
  646. // Should apply the current opacity and location to all elements so we can update them again for an animation
  647. _forceLayout: function () {
  648. //In my testing this works, infact offsetWidth of any element seems to work.
  649. //Could loop all this._layers and do this for each _icon if it stops working
  650. L.Util.falseFn(document.body.offsetWidth);
  651. }
  652. });
  653. L.MarkerCluster = L.Marker.extend({
  654. initialize: function (group, zoom, a, b) {
  655. L.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new L.LatLng(0, 0), { icon: this });
  656. this._group = group;
  657. this._zoom = zoom;
  658. this._markers = [];
  659. this._childClusters = [];
  660. this._childCount = 0;
  661. this._iconNeedsUpdate = true;
  662. this._bounds = new L.LatLngBounds();
  663. if (a) {
  664. this._addChild(a);
  665. }
  666. if (b) {
  667. this._addChild(b);
  668. }
  669. },
  670. //Recursively retrieve all child markers of this cluster
  671. getAllChildMarkers: function (storageArray) {
  672. storageArray = storageArray || [];
  673. for (var i = this._childClusters.length - 1; i >= 0; i--) {
  674. this._childClusters[i].getAllChildMarkers(storageArray);
  675. }
  676. for (var j = this._markers.length - 1; j >= 0; j--) {
  677. storageArray.push(this._markers[j]);
  678. }
  679. return storageArray;
  680. },
  681. //Returns the count of how many child markers we have
  682. getChildCount: function () {
  683. return this._childCount;
  684. },
  685. //Zoom to the extents of this cluster
  686. zoomToBounds: function () {
  687. this._group._map.fitBounds(this._bounds);
  688. },
  689. _updateIcon: function () {
  690. this._iconNeedsUpdate = true;
  691. if (this._icon) {
  692. this.setIcon(this);
  693. }
  694. },
  695. //Cludge for Icon, we pretend to be an icon for performance
  696. createIcon: function () {
  697. if (this._iconNeedsUpdate) {
  698. this._iconObj = this._group.options.iconCreateFunction(this);
  699. this._iconNeedsUpdate = false;
  700. }
  701. return this._iconObj.createIcon();
  702. },
  703. createShadow: function () {
  704. return this._iconObj.createShadow();
  705. },
  706. _addChild: function (new1, isNotificationFromChild) {
  707. this._iconNeedsUpdate = true;
  708. this._expandBounds(new1);
  709. if (new1 instanceof L.MarkerCluster) {
  710. if (!isNotificationFromChild) {
  711. this._childClusters.push(new1);
  712. new1.__parent = this;
  713. }
  714. this._childCount += new1._childCount;
  715. } else {
  716. if (!isNotificationFromChild) {
  717. this._markers.push(new1);
  718. }
  719. this._childCount++;
  720. }
  721. if (this.__parent) {
  722. this.__parent._addChild(new1, true);
  723. }
  724. },
  725. //Expand our bounds and tell our parent to
  726. _expandBounds: function (marker) {
  727. var addedCount,
  728. addedLatLng = marker._wLatLng || marker._latlng;
  729. if (marker instanceof L.MarkerCluster) {
  730. this._bounds.extend(marker._bounds);
  731. addedCount = marker._childCount;
  732. } else {
  733. this._bounds.extend(addedLatLng);
  734. addedCount = 1;
  735. }
  736. if (!this._cLatLng) {
  737. // when clustering, take position of the first point as the cluster center
  738. this._cLatLng = marker._cLatLng || addedLatLng;
  739. }
  740. // when showing clusters, take weighted average of all points as cluster center
  741. var totalCount = this._childCount + addedCount;
  742. //Calculate weighted latlng for display
  743. if (!this._wLatLng) {
  744. this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng);
  745. } else {
  746. this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount;
  747. this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount;
  748. }
  749. },
  750. //Set our markers position as given and add it to the map
  751. _addToMap: function (startPos) {
  752. if (startPos) {
  753. this._backupLatlng = this._latlng;
  754. this.setLatLng(startPos);
  755. }
  756. L.FeatureGroup.prototype.addLayer.call(this._group, this);
  757. },
  758. _recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) {
  759. this._recursively(bounds, 0, maxZoom - 1,
  760. function (c) {
  761. var markers = c._markers,
  762. i, m;
  763. for (i = markers.length - 1; i >= 0; i--) {
  764. m = markers[i];
  765. //Only do it if the icon is still on the map
  766. if (m._icon) {
  767. m._setPos(center);
  768. m.setOpacity(0);
  769. }
  770. }
  771. },
  772. function (c) {
  773. var childClusters = c._childClusters,
  774. j, cm;
  775. for (j = childClusters.length - 1; j >= 0; j--) {
  776. cm = childClusters[j];
  777. if (cm._icon) {
  778. cm._setPos(center);
  779. cm.setOpacity(0);
  780. }
  781. }
  782. }
  783. );
  784. },
  785. _recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, previousZoomLevel, newZoomLevel) {
  786. this._recursively(bounds, newZoomLevel, 0,
  787. function (c) {
  788. c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel);
  789. //TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be.
  790. //As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate
  791. if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) {
  792. c.setOpacity(1);
  793. c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds
  794. } else {
  795. c.setOpacity(0);
  796. }
  797. c._addToMap();
  798. }
  799. );
  800. },
  801. _recursivelyBecomeVisible: function (bounds, zoomLevel) {
  802. this._recursively(bounds, 0, zoomLevel, null, function (c) {
  803. c.setOpacity(1);
  804. });
  805. },
  806. _recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) {
  807. this._recursively(bounds, -1, zoomLevel,
  808. function (c) {
  809. if (zoomLevel === c._zoom) {
  810. return;
  811. }
  812. //Add our child markers at startPos (so they can be animated out)
  813. for (var i = c._markers.length - 1; i >= 0; i--) {
  814. var nm = c._markers[i];
  815. if (!bounds.contains(nm._latlng)) {
  816. continue;
  817. }
  818. if (startPos) {
  819. nm._backupLatlng = nm.getLatLng();
  820. nm.setLatLng(startPos);
  821. nm.setOpacity(0);
  822. }
  823. L.FeatureGroup.prototype.addLayer.call(c._group, nm);
  824. }
  825. },
  826. function (c) {
  827. c._addToMap(startPos);
  828. }
  829. );
  830. },
  831. _recursivelyRestoreChildPositions: function (zoomLevel) {
  832. //Fix positions of child markers
  833. for (var i = this._markers.length - 1; i >= 0; i--) {
  834. var nm = this._markers[i];
  835. if (nm._backupLatlng) {
  836. nm.setLatLng(nm._backupLatlng);
  837. delete nm._backupLatlng;
  838. }
  839. }
  840. if (zoomLevel - 1 === this._zoom) {
  841. //Reposition child clusters
  842. for (var j = this._childClusters.length - 1; j >= 0; j--) {
  843. this._childClusters[j]._restorePosition();
  844. }
  845. } else {
  846. for (var k = this._childClusters.length - 1; k >= 0; k--) {
  847. this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel);
  848. }
  849. }
  850. },
  851. _restorePosition: function () {
  852. if (this._backupLatlng) {
  853. this.setLatLng(this._backupLatlng);
  854. delete this._backupLatlng;
  855. }
  856. },
  857. //exceptBounds: If set, don't remove any markers/clusters in it
  858. _recursivelyRemoveChildrenFromMap: function (previousBounds, zoomLevel, exceptBounds) {
  859. var m, i;
  860. this._recursively(previousBounds, -1, zoomLevel - 1,
  861. function (c) {
  862. //Remove markers at every level
  863. for (i = c._markers.length - 1; i >= 0; i--) {
  864. m = c._markers[i];
  865. if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
  866. L.FeatureGroup.prototype.removeLayer.call(c._group, m);
  867. m.setOpacity(1);
  868. }
  869. }
  870. },
  871. function (c) {
  872. //Remove child clusters at just the bottom level
  873. for (i = c._childClusters.length - 1; i >= 0; i--) {
  874. m = c._childClusters[i];
  875. if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
  876. L.FeatureGroup.prototype.removeLayer.call(c._group, m);
  877. m.setOpacity(1);
  878. }
  879. }
  880. }
  881. );
  882. },
  883. //Run the given functions recursively to this and child clusters
  884. // boundsToApplyTo: a L.LatLngBounds representing the bounds of what clusters to recurse in to
  885. // zoomLevelToStart: zoom level to start running functions (inclusive)
  886. // zoomLevelToStop: zoom level to stop running functions (inclusive)
  887. // runAtEveryLevel: function that takes an L.MarkerCluster as an argument that should be applied on every level
  888. // runAtBottomLevel: function that takes an L.MarkerCluster as an argument that should be applied at only the bottom level
  889. _recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) {
  890. var childClusters = this._childClusters,
  891. zoom = this._zoom,
  892. i, c;
  893. if (zoomLevelToStart > zoom) { //Still going down to required depth, just recurse to child clusters
  894. for (i = childClusters.length - 1; i >= 0; i--) {
  895. c = childClusters[i];
  896. if (boundsToApplyTo.intersects(c._bounds)) {
  897. c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
  898. }
  899. }
  900. } else { //In required depth
  901. if (runAtEveryLevel) {
  902. runAtEveryLevel(this);
  903. }
  904. if (runAtBottomLevel && this._zoom === zoomLevelToStop) {
  905. runAtBottomLevel(this);
  906. }
  907. //TODO: This loop is almost the same as above
  908. if (zoomLevelToStop > zoom) {
  909. for (i = childClusters.length - 1; i >= 0; i--) {
  910. c = childClusters[i];
  911. if (boundsToApplyTo.intersects(c._bounds)) {
  912. c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
  913. }
  914. }
  915. }
  916. }
  917. },
  918. _recalculateBounds: function () {
  919. var markers = this._markers,
  920. childClusters = this._childClusters,
  921. i;
  922. this._bounds = new L.LatLngBounds();
  923. delete this._wLatLng;
  924. for (i = markers.length - 1; i >= 0; i--) {
  925. this._expandBounds(markers[i]);
  926. }
  927. for (i = childClusters.length - 1; i >= 0; i--) {
  928. this._expandBounds(childClusters[i]);
  929. }
  930. },
  931. //Returns true if we are the parent of only one cluster and that cluster is the same as us
  932. _isSingleParent: function () {
  933. //Don't need to check this._markers as the rest won't work if there are any
  934. return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount;
  935. }
  936. });
  937. L.DistanceGrid = function (cellSize) {
  938. this._cellSize = cellSize;
  939. this._sqCellSize = cellSize * cellSize;
  940. this._grid = {};
  941. this._objectPoint = { };
  942. };
  943. L.DistanceGrid.prototype = {
  944. addObject: function (obj, point) {
  945. var x = this._getCoord(point.x),
  946. y = this._getCoord(point.y),
  947. grid = this._grid,
  948. row = grid[y] = grid[y] || {},
  949. cell = row[x] = row[x] || [],
  950. stamp = L.Util.stamp(obj);
  951. this._objectPoint[stamp] = point;
  952. cell.push(obj);
  953. },
  954. updateObject: function (obj, point) {
  955. this.removeObject(obj);
  956. this.addObject(obj, point);
  957. },
  958. //Returns true if the object was found
  959. removeObject: function (obj, point) {
  960. var x = this._getCoord(point.x),
  961. y = this._getCoord(point.y),
  962. grid = this._grid,
  963. row = grid[y] = grid[y] || {},
  964. cell = row[x] = row[x] || [],
  965. i, len;
  966. delete this._objectPoint[L.Util.stamp(obj)];
  967. for (i = 0, len = cell.length; i < len; i++) {
  968. if (cell[i] === obj) {
  969. cell.splice(i, 1);
  970. if (len === 1) {
  971. delete row[x];
  972. }
  973. return true;
  974. }
  975. }
  976. },
  977. eachObject: function (fn, context) {
  978. var i, j, k, len, row, cell, removed,
  979. grid = this._grid;
  980. for (i in grid) {
  981. if (grid.hasOwnProperty(i)) {
  982. row = grid[i];
  983. for (j in row) {
  984. if (row.hasOwnProperty(j)) {
  985. cell = row[j];
  986. for (k = 0, len = cell.length; k < len; k++) {
  987. removed = fn.call(context, cell[k]);
  988. if (removed) {
  989. k--;
  990. len--;
  991. }
  992. }
  993. }
  994. }
  995. }
  996. }
  997. },
  998. getNearObject: function (point) {
  999. var x = this._getCoord(point.x),
  1000. y = this._getCoord(point.y),
  1001. i, j, k, row, cell, len, obj, dist,
  1002. objectPoint = this._objectPoint,
  1003. closestDistSq = this._sqCellSize,
  1004. closest = null;
  1005. for (i = y - 1; i <= y + 1; i++) {
  1006. row = this._grid[i];
  1007. if (row) {
  1008. for (j = x - 1; j <= x + 1; j++) {
  1009. cell = row[j];
  1010. if (cell) {
  1011. for (k = 0, len = cell.length; k < len; k++) {
  1012. obj = cell[k];
  1013. dist = this._sqDist(objectPoint[L.Util.stamp(obj)], point);
  1014. if (dist < closestDistSq) {
  1015. closestDistSq = dist;
  1016. closest = obj;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. return closest;
  1024. },
  1025. _getCoord: function (x) {
  1026. return Math.floor(x / this._cellSize);
  1027. },
  1028. _sqDist: function (p, p2) {
  1029. var dx = p2.x - p.x,
  1030. dy = p2.y - p.y;
  1031. return dx * dx + dy * dy;
  1032. }
  1033. };
  1034. /* Copyright (c) 2012 the authors listed at the following URL, and/or
  1035. the authors of referenced articles or incorporated external code:
  1036. http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256
  1037. Permission is hereby granted, free of charge, to any person obtaining
  1038. a copy of this software and associated documentation files (the
  1039. "Software"), to deal in the Software without restriction, including
  1040. without limitation the rights to use, copy, modify, merge, publish,
  1041. distribute, sublicense, and/or sell copies of the Software, and to
  1042. permit persons to whom the Software is furnished to do so, subject to
  1043. the following conditions:
  1044. The above copyright notice and this permission notice shall be
  1045. included in all copies or substantial portions of the Software.
  1046. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  1047. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1048. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  1049. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  1050. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  1051. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  1052. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1053. Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434
  1054. */
  1055. (function () {
  1056. L.QuickHull = {
  1057. getDistant: function (cpt, bl) {
  1058. var vY = bl[1].lat - bl[0].lat,
  1059. vX = bl[0].lng - bl[1].lng;
  1060. return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng));
  1061. },
  1062. findMostDistantPointFromBaseLine: function (baseLine, latLngs) {
  1063. var maxD = 0,
  1064. maxPt = null,
  1065. newPoints = [],
  1066. i, pt, d;
  1067. for (i = latLngs.length - 1; i >= 0; i--) {
  1068. pt = latLngs[i];
  1069. d = this.getDistant(pt, baseLine);
  1070. if (d > 0) {
  1071. newPoints.push(pt);
  1072. } else {
  1073. continue;
  1074. }
  1075. if (d > maxD) {
  1076. maxD = d;
  1077. maxPt = pt;
  1078. }
  1079. }
  1080. return { 'maxPoint': maxPt, 'newPoints': newPoints };
  1081. },
  1082. buildConvexHull: function (baseLine, latLngs) {
  1083. var convexHullBaseLines = [],
  1084. t = this.findMostDistantPointFromBaseLine(baseLine, latLngs);
  1085. if (t.maxPoint) { // if there is still a point "outside" the base line
  1086. convexHullBaseLines =
  1087. convexHullBaseLines.concat(
  1088. this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints)
  1089. );
  1090. convexHullBaseLines =
  1091. convexHullBaseLines.concat(
  1092. this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints)
  1093. );
  1094. return convexHullBaseLines;
  1095. } else { // if there is no more point "outside" the base line, the current base line is part of the convex hull
  1096. return [baseLine];
  1097. }
  1098. },
  1099. getConvexHull: function (latLngs) {
  1100. //find first baseline
  1101. var maxLat = false, minLat = false,
  1102. maxPt = null, minPt = null,
  1103. i;
  1104. for (i = latLngs.length - 1; i >= 0; i--) {
  1105. var pt = latLngs[i];
  1106. if (maxLat === false || pt.lat > maxLat) {
  1107. maxPt = pt;
  1108. maxLat = pt.lat;
  1109. }
  1110. if (minLat === false || pt.lat < minLat) {
  1111. minPt = pt;
  1112. minLat = pt.lat;
  1113. }
  1114. }
  1115. var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs),
  1116. this.buildConvexHull([maxPt, minPt], latLngs));
  1117. return ch;
  1118. }
  1119. };
  1120. }());
  1121. L.MarkerCluster.include({
  1122. getConvexHull: function () {
  1123. var childMarkers = this.getAllChildMarkers(),
  1124. points = [],
  1125. hullLatLng = [],
  1126. hull, p, i;
  1127. for (i = childMarkers.length - 1; i >= 0; i--) {
  1128. p = childMarkers[i].getLatLng();
  1129. points.push(p);
  1130. }
  1131. hull = L.QuickHull.getConvexHull(points);
  1132. for (i = hull.length - 1; i >= 0; i--) {
  1133. hullLatLng.push(hull[i][0]);
  1134. }
  1135. return hullLatLng;
  1136. }
  1137. });
  1138. //This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
  1139. //Huge thanks to jawj for implementing it first to make my job easy :-)
  1140. L.MarkerCluster.include({
  1141. _2PI: Math.PI * 2,
  1142. _circleFootSeparation: 25, //related to circumference of circle
  1143. _circleStartAngle: Math.PI / 6,
  1144. _spiralFootSeparation: 28, //related to size of spiral (experiment!)
  1145. _spiralLengthStart: 11,
  1146. _spiralLengthFactor: 5,
  1147. _circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards.
  1148. // 0 -> always spiral; Infinity -> always circle
  1149. spiderfy: function () {
  1150. if (this._group._spiderfied === this || this._group._inZoomAnimation) {
  1151. return;
  1152. }
  1153. var childMarkers = this.getAllChildMarkers(),
  1154. group = this._group,
  1155. map = group._map,
  1156. center = map.latLngToLayerPoint(this._latlng),
  1157. positions;
  1158. this._group._unspiderfy();
  1159. this._group._spiderfied = this;
  1160. //TODO Maybe: childMarkers order by distance to center
  1161. if (childMarkers.length >= this._circleSpiralSwitchover) {
  1162. positions = this._generatePointsSpiral(childMarkers.length, center);
  1163. } else {
  1164. center.y += 10; //Otherwise circles look wrong
  1165. positions = this._generatePointsCircle(childMarkers.length, center);
  1166. }
  1167. this._animationSpiderfy(childMarkers, positions);
  1168. },
  1169. unspiderfy: function (zoomDetails) {
  1170. /// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param>
  1171. if (this._group._inZoomAnimation) {
  1172. return;
  1173. }
  1174. this._animationUnspiderfy(zoomDetails);
  1175. this._group._spiderfied = null;
  1176. },
  1177. _generatePointsCircle: function (count, centerPt) {
  1178. var circumference = this._circleFootSeparation * (2 + count),
  1179. legLength = circumference / this._2PI, //radius from circumference
  1180. angleStep = this._2PI / count,
  1181. res = [],
  1182. i, angle;
  1183. res.length = count;
  1184. for (i = count - 1; i >= 0; i--) {
  1185. angle = this._circleStartAngle + i * angleStep;
  1186. res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
  1187. }
  1188. return res;
  1189. },
  1190. _generatePointsSpiral: function (count, centerPt) {
  1191. var legLength = this._spiralLengthStart,
  1192. angle = 0,
  1193. res = [],
  1194. i;
  1195. res.length = count;
  1196. for (i = count - 1; i >= 0; i--) {
  1197. angle += this._spiralFootSeparation / legLength + i * 0.0005;
  1198. res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
  1199. legLength += this._2PI * this._spiralLengthFactor / angle;
  1200. }
  1201. return res;
  1202. }
  1203. });
  1204. L.MarkerCluster.include(!L.DomUtil.TRANSITION ? {
  1205. //Non Animated versions of everything
  1206. _animationSpiderfy: function (childMarkers, positions) {
  1207. var group = this._group,
  1208. map = group._map,
  1209. i, m, leg, newPos;
  1210. for (i = childMarkers.length - 1; i >= 0; i--) {
  1211. newPos = map.layerPointToLatLng(positions[i]);
  1212. m = childMarkers[i];
  1213. m._preSpiderfyLatlng = m._latlng;
  1214. m.setLatLng(newPos);
  1215. m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
  1216. L.FeatureGroup.prototype.addLayer.call(group, m);
  1217. leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' });
  1218. map.addLayer(leg);
  1219. m._spiderLeg = leg;
  1220. }
  1221. this.setOpacity(0.3);
  1222. group.fire('spiderfied');
  1223. },
  1224. _animationUnspiderfy: function () {
  1225. var group = this._group,
  1226. map = group._map,
  1227. childMarkers = this.getAllChildMarkers(),
  1228. m, i;
  1229. this.setOpacity(1);
  1230. for (i = childMarkers.length - 1; i >= 0; i--) {
  1231. m = childMarkers[i];
  1232. L.FeatureGroup.prototype.removeLayer.call(group, m);
  1233. m.setLatLng(m._preSpiderfyLatlng);
  1234. delete m._preSpiderfyLatlng;
  1235. m.setZIndexOffset(0);
  1236. map.removeLayer(m._spiderLeg);
  1237. delete m._spiderLeg;
  1238. }
  1239. }
  1240. } : {
  1241. //Animated versions here
  1242. _animationSpiderfy: function (childMarkers, positions) {
  1243. var me = this,
  1244. group = this._group,
  1245. map = group._map,
  1246. thisLayerPos = map.latLngToLayerPoint(this._latlng),
  1247. i, m, leg, newPos;
  1248. //Add markers to map hidden at our center point
  1249. for (i = childMarkers.length - 1; i >= 0; i--) {
  1250. m = childMarkers[i];
  1251. m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
  1252. m.setOpacity(0);
  1253. L.FeatureGroup.prototype.addLayer.call(group, m);
  1254. m._setPos(thisLayerPos);
  1255. }
  1256. group._forceLayout();
  1257. group._animationStart();
  1258. var initialLegOpacity = L.Path.SVG ? 0 : 0.3,
  1259. xmlns = L.Path.SVG_NS;
  1260. for (i = childMarkers.length - 1; i >= 0; i--) {
  1261. newPos = map.layerPointToLatLng(positions[i]);
  1262. m = childMarkers[i];
  1263. //Move marker to new position
  1264. m._preSpiderfyLatlng = m._latlng;
  1265. m.setLatLng(newPos);
  1266. m.setOpacity(1);
  1267. //Add Legs.
  1268. leg = new L.Polyline([me._latlng, newPos], { weight: 1.5, color: '#222', opacity: initialLegOpacity });
  1269. map.addLayer(leg);
  1270. m._spiderLeg = leg;
  1271. //Following animations don't work for canvas
  1272. if (!L.Path.SVG) {
  1273. continue;
  1274. }
  1275. //How this works:
  1276. //http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios
  1277. //http://dev.opera.com/articles/view/advanced-svg-animation-techniques/
  1278. //Animate length
  1279. var length = leg._path.getTotalLength();
  1280. leg._path.setAttribute("stroke-dasharray", length + "," + length);
  1281. var anim = document.createElementNS(xmlns, "animate");
  1282. anim.setAttribute("attributeName", "stroke-dashoffset");
  1283. anim.setAttribute("begin", "indefinite");
  1284. anim.setAttribute("from", length);
  1285. anim.setAttribute("to", 0);
  1286. anim.setAttribute("dur", 0.25);
  1287. leg._path.appendChild(anim);
  1288. anim.beginElement();
  1289. //Animate opacity
  1290. anim = document.createElementNS(xmlns, "animate");
  1291. anim.setAttribute("attributeName", "stroke-opacity");
  1292. anim.setAttribute("attributeName", "stroke-opacity");
  1293. anim.setAttribute("begin", "indefinite");
  1294. anim.setAttribute("from", 0);
  1295. anim.setAttribute("to", 0.5);
  1296. anim.setAttribute("dur", 0.25);
  1297. leg._path.appendChild(anim);
  1298. anim.beginElement();
  1299. }
  1300. me.setOpacity(0.3);
  1301. //Set the opacity of the spiderLegs back to their correct value
  1302. // The animations above override this until they complete.
  1303. // If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts.
  1304. if (L.Path.SVG) {
  1305. this._group._forceLayout();
  1306. for (i = childMarkers.length - 1; i >= 0; i--) {
  1307. m = childMarkers[i]._spiderLeg;
  1308. m.options.opacity = 0.5;
  1309. m._path.setAttribute('stroke-opacity', 0.5);
  1310. }
  1311. }
  1312. setTimeout(function () {
  1313. group._animationEnd();
  1314. group.fire('spiderfied');
  1315. }, 250);
  1316. },
  1317. _animationUnspiderfy: function (zoomDetails) {
  1318. var group = this._group,
  1319. map = group._map,
  1320. thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng),
  1321. childMarkers = this.getAllChildMarkers(),
  1322. svg = L.Path.SVG,
  1323. m, i, a;
  1324. group._animationStart();
  1325. //Make us visible and bring the child markers back in
  1326. this.setOpacity(1);
  1327. for (i = childMarkers.length - 1; i >= 0; i--) {
  1328. m = childMarkers[i];
  1329. //Fix up the location to the real one
  1330. m.setLatLng(m._preSpiderfyLatlng);
  1331. delete m._preSpiderfyLatlng;
  1332. //Hack override the location to be our center
  1333. m._setPos(thisLayerPos);
  1334. m.setOpacity(0);
  1335. //Animate the spider legs back in
  1336. if (svg) {
  1337. a = m._spiderLeg._path.childNodes[0];
  1338. a.setAttribute('to', a.getAttribute('from'));
  1339. a.setAttribute('from', 0);
  1340. a.beginElement();
  1341. a = m._spiderLeg._path.childNodes[1];
  1342. a.setAttribute('from', 0.5);
  1343. a.setAttribute('to', 0);
  1344. a.setAttribute('stroke-opacity', 0);
  1345. a.beginElement();
  1346. m._spiderLeg._path.setAttribute('stroke-opacity', 0);
  1347. }
  1348. }
  1349. setTimeout(function () {
  1350. //If we have only <= one child left then that marker will be shown on the map so don't remove it!
  1351. var stillThereChildCount = 0;
  1352. for (i = childMarkers.length - 1; i >= 0; i--) {
  1353. m = childMarkers[i];
  1354. if (m._spiderLeg) {
  1355. stillThereChildCount++;
  1356. }
  1357. }
  1358. for (i = childMarkers.length - 1; i >= 0; i--) {
  1359. m = childMarkers[i];
  1360. if (!m._spiderLeg) { //Has already been unspiderfied
  1361. continue;
  1362. }
  1363. m.setOpacity(1);
  1364. m.setZIndexOffset(0);
  1365. if (stillThereChildCount > 1) {
  1366. L.FeatureGroup.prototype.removeLayer.call(group, m);
  1367. }
  1368. map.removeLayer(m._spiderLeg);
  1369. delete m._spiderLeg;
  1370. }
  1371. group._animationEnd();
  1372. }, 250);
  1373. }
  1374. });
  1375. L.MarkerClusterGroup.include({
  1376. //The MarkerCluster currently spiderfied (if any)
  1377. _spiderfied: null,
  1378. _spiderfierOnAdd: function () {
  1379. this._map.on('click', this._unspiderfyWrapper, this);
  1380. if (this._map.options.zoomAnimation) {
  1381. this._map.on('zoomstart', this._unspiderfyZoomStart, this);
  1382. } else {
  1383. //Browsers without zoomAnimation don't fire zoomstart
  1384. this._map.on('zoomend', this._unspiderfyWrapper, this);
  1385. }
  1386. if (L.Path.SVG && !L.Browser.touch) {
  1387. this._map._initPathRoot();
  1388. //Needs to happen in the pageload, not after, or animations don't work in webkit
  1389. // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements
  1390. //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable
  1391. }
  1392. },
  1393. _spiderfierOnRemove: function () {
  1394. this._map.off('click', this._unspiderfyWrapper, this);
  1395. this._map.off('zoomstart', this._unspiderfyZoomStart, this);
  1396. this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
  1397. this._unspiderfy(); //Ensure that markers are back where they should be
  1398. },
  1399. //On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated)
  1400. //This means we can define the animation they do rather than Markers doing an animation to their actual location
  1401. _unspiderfyZoomStart: function () {
  1402. if (!this._map) { //May have been removed from the map by a zoomEnd handler
  1403. return;
  1404. }
  1405. this._map.on('zoomanim', this._unspiderfyZoomAnim, this);
  1406. },
  1407. _unspiderfyZoomAnim: function (zoomDetails) {
  1408. //Wait until the first zoomanim after the user has finished touch-zooming before running the animation
  1409. if (L.DomUtil.hasClass(this._map._mapPane, 'leaflet-touching')) {
  1410. return;
  1411. }
  1412. this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
  1413. this._unspiderfy(zoomDetails);
  1414. },
  1415. _unspiderfyWrapper: function () {
  1416. /// <summary>_unspiderfy but passes no arguments</summary>
  1417. this._unspiderfy();
  1418. },
  1419. _unspiderfy: function (zoomDetails) {
  1420. if (this._spiderfied) {
  1421. this._spiderfied.unspiderfy(zoomDetails);
  1422. }
  1423. },
  1424. //If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
  1425. _unspiderfyLayer: function (layer) {
  1426. if (layer._spiderLeg) {
  1427. L.FeatureGroup.prototype.removeLayer.call(this, layer);
  1428. layer.setOpacity(1);
  1429. //Position will be fixed up immediately in _animationUnspiderfy
  1430. layer.setZIndexOffset(0);
  1431. this._map.removeLayer(layer._spiderLeg);
  1432. delete layer._spiderLeg;
  1433. }
  1434. }
  1435. });
  1436. }(this));