Advertisement
Guest User

Working Leaflet.markercluster-src.js for 1.0 beta 1

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