/examples/lib/markercluster/leaflet.markercluster-src.js

https://github.com/profilemeup/esri-leaflet · JavaScript · 2006 lines · 1444 code · 373 blank · 189 comment · 278 complexity · 6e0eca953f00be5062290de21aee672b MD5 · raw file

Large files are truncated click here to view the full file

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