12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015 |
- /*
- Leaflet.markercluster, Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps.
- https://github.com/Leaflet/Leaflet.markercluster
- (c) 2012-2013, Dave Leaver, smartrak
- */
- (function (window, document, undefined) {
- /*
- * L.MarkerClusterGroup extends L.FeatureGroup by clustering the markers contained within
- */
- L.MarkerClusterGroup = L.FeatureGroup.extend({
- options: {
- maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center
- iconCreateFunction: null,
- spiderfyOnMaxZoom: true,
- showCoverageOnHover: true,
- zoomToBoundsOnClick: true,
- singleMarkerMode: false,
- disableClusteringAtZoom: null,
- // Setting this to false prevents the removal of any clusters outside of the viewpoint, which
- // is the default behaviour for performance reasons.
- removeOutsideVisibleBounds: true,
- //Whether to animate adding markers after adding the MarkerClusterGroup to the map
- // If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains.
- animateAddingMarkers: false,
- //Increase to increase the distance away that spiderfied markers appear from the center
- spiderfyDistanceMultiplier: 1,
- //Options to pass to the L.Polygon constructor
- polygonOptions: {}
- },
- initialize: function (options) {
- L.Util.setOptions(this, options);
- if (!this.options.iconCreateFunction) {
- this.options.iconCreateFunction = this._defaultIconCreateFunction;
- }
- this._featureGroup = L.featureGroup();
- this._featureGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
- this._nonPointGroup = L.featureGroup();
- this._nonPointGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
- this._inZoomAnimation = 0;
- this._needsClustering = [];
- this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of
- //The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
- this._currentShownBounds = null;
- },
- addLayer: function (layer) {
- if (layer instanceof L.LayerGroup) {
- var array = [];
- for (var i in layer._layers) {
- array.push(layer._layers[i]);
- }
- return this.addLayers(array);
- }
- //Don't cluster non point data
- if (!layer.getLatLng) {
- this._nonPointGroup.addLayer(layer);
- return this;
- }
- if (!this._map) {
- this._needsClustering.push(layer);
- return this;
- }
- if (this.hasLayer(layer)) {
- return this;
- }
- //If we have already clustered we'll need to add this one to a cluster
- if (this._unspiderfy) {
- this._unspiderfy();
- }
- this._addLayer(layer, this._maxZoom);
- //Work out what is visible
- var visibleLayer = layer,
- currentZoom = this._map.getZoom();
- if (layer.__parent) {
- while (visibleLayer.__parent._zoom >= currentZoom) {
- visibleLayer = visibleLayer.__parent;
- }
- }
- if (this._currentShownBounds.contains(visibleLayer.getLatLng())) {
- if (this.options.animateAddingMarkers) {
- this._animationAddLayer(layer, visibleLayer);
- } else {
- this._animationAddLayerNonAnimated(layer, visibleLayer);
- }
- }
- return this;
- },
- removeLayer: function (layer) {
- if (layer instanceof L.LayerGroup)
- {
- var array = [];
- for (var i in layer._layers) {
- array.push(layer._layers[i]);
- }
- return this.removeLayers(array);
- }
- //Non point layers
- if (!layer.getLatLng) {
- this._nonPointGroup.removeLayer(layer);
- return this;
- }
- if (!this._map) {
- if (!this._arraySplice(this._needsClustering, layer) && this.hasLayer(layer)) {
- this._needsRemoving.push(layer);
- }
- return this;
- }
- if (!layer.__parent) {
- return this;
- }
- if (this._unspiderfy) {
- this._unspiderfy();
- this._unspiderfyLayer(layer);
- }
- //Remove the marker from clusters
- this._removeLayer(layer, true);
- if (this._featureGroup.hasLayer(layer)) {
- this._featureGroup.removeLayer(layer);
- if (layer.setOpacity) {
- layer.setOpacity(1);
- }
- }
- return this;
- },
- //Takes an array of markers and adds them in bulk
- addLayers: function (layersArray) {
- var i, l, m,
- onMap = this._map,
- fg = this._featureGroup,
- npg = this._nonPointGroup;
- for (i = 0, l = layersArray.length; i < l; i++) {
- m = layersArray[i];
- //Not point data, can't be clustered
- if (!m.getLatLng) {
- npg.addLayer(m);
- continue;
- }
- if (this.hasLayer(m)) {
- continue;
- }
- if (!onMap) {
- this._needsClustering.push(m);
- continue;
- }
- this._addLayer(m, this._maxZoom);
- //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
- if (m.__parent) {
- if (m.__parent.getChildCount() === 2) {
- var markers = m.__parent.getAllChildMarkers(),
- otherMarker = markers[0] === m ? markers[1] : markers[0];
- fg.removeLayer(otherMarker);
- }
- }
- }
- if (onMap) {
- //Update the icons of all those visible clusters that were affected
- fg.eachLayer(function (c) {
- if (c instanceof L.MarkerCluster && c._iconNeedsUpdate) {
- c._updateIcon();
- }
- });
- this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
- }
- return this;
- },
- //Takes an array of markers and removes them in bulk
- removeLayers: function (layersArray) {
- var i, l, m,
- fg = this._featureGroup,
- npg = this._nonPointGroup;
- if (!this._map) {
- for (i = 0, l = layersArray.length; i < l; i++) {
- m = layersArray[i];
- this._arraySplice(this._needsClustering, m);
- npg.removeLayer(m);
- }
- return this;
- }
- for (i = 0, l = layersArray.length; i < l; i++) {
- m = layersArray[i];
- if (!m.__parent) {
- npg.removeLayer(m);
- continue;
- }
- this._removeLayer(m, true, true);
- if (fg.hasLayer(m)) {
- fg.removeLayer(m);
- if (m.setOpacity) {
- m.setOpacity(1);
- }
- }
- }
- //Fix up the clusters and markers on the map
- this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
- fg.eachLayer(function (c) {
- if (c instanceof L.MarkerCluster) {
- c._updateIcon();
- }
- });
- return this;
- },
- //Removes all layers from the MarkerClusterGroup
- clearLayers: function () {
- //Need our own special implementation as the LayerGroup one doesn't work for us
- //If we aren't on the map (yet), blow away the markers we know of
- if (!this._map) {
- this._needsClustering = [];
- delete this._gridClusters;
- delete this._gridUnclustered;
- }
- if (this._noanimationUnspiderfy) {
- this._noanimationUnspiderfy();
- }
- //Remove all the visible layers
- this._featureGroup.clearLayers();
- this._nonPointGroup.clearLayers();
- this.eachLayer(function (marker) {
- delete marker.__parent;
- });
- if (this._map) {
- //Reset _topClusterLevel and the DistanceGrids
- this._generateInitialClusters();
- }
- return this;
- },
- //Override FeatureGroup.getBounds as it doesn't work
- getBounds: function () {
- var bounds = new L.LatLngBounds();
- if (this._topClusterLevel) {
- bounds.extend(this._topClusterLevel._bounds);
- } else {
- for (var i = this._needsClustering.length - 1; i >= 0; i--) {
- bounds.extend(this._needsClustering[i].getLatLng());
- }
- }
- //TODO: Can remove this isValid test when leaflet 0.6 is released
- var nonPointBounds = this._nonPointGroup.getBounds();
- if (nonPointBounds.isValid()) {
- bounds.extend(nonPointBounds);
- }
- return bounds;
- },
- //Overrides LayerGroup.eachLayer
- eachLayer: function (method, context) {
- var markers = this._needsClustering.slice(),
- i;
- if (this._topClusterLevel) {
- this._topClusterLevel.getAllChildMarkers(markers);
- }
- for (i = markers.length - 1; i >= 0; i--) {
- method.call(context, markers[i]);
- }
- this._nonPointGroup.eachLayer(method, context);
- },
- //Returns true if the given layer is in this MarkerClusterGroup
- hasLayer: function (layer) {
- if (!layer) {
- return false;
- }
- var i, anArray = this._needsClustering;
- for (i = anArray.length - 1; i >= 0; i--) {
- if (anArray[i] === layer) {
- return true;
- }
- }
- anArray = this._needsRemoving;
- for (i = anArray.length - 1; i >= 0; i--) {
- if (anArray[i] === layer) {
- return false;
- }
- }
- return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer);
- },
- //Zoom down to show the given layer (spiderfying if necessary) then calls the callback
- zoomToShowLayer: function (layer, callback) {
- var showMarker = function () {
- if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) {
- this._map.off('moveend', showMarker, this);
- this.off('animationend', showMarker, this);
- if (layer._icon) {
- callback();
- } else if (layer.__parent._icon) {
- var afterSpiderfy = function () {
- this.off('spiderfied', afterSpiderfy, this);
- callback();
- };
- this.on('spiderfied', afterSpiderfy, this);
- layer.__parent.spiderfy();
- }
- }
- };
- if (layer._icon) {
- callback();
- } else if (layer.__parent._zoom < this._map.getZoom()) {
- //Layer should be visible now but isn't on screen, just pan over to it
- this._map.on('moveend', showMarker, this);
- if (!layer._icon) {
- this._map.panTo(layer.getLatLng());
- }
- } else {
- this._map.on('moveend', showMarker, this);
- this.on('animationend', showMarker, this);
- this._map.setView(layer.getLatLng(), layer.__parent._zoom + 1);
- layer.__parent.zoomToBounds();
- }
- },
- //Overrides FeatureGroup.onAdd
- onAdd: function (map) {
- this._map = map;
- var i, l, layer;
- if (!isFinite(this._map.getMaxZoom())) {
- throw "Map has no maxZoom specified";
- }
- this._featureGroup.onAdd(map);
- this._nonPointGroup.onAdd(map);
- if (!this._gridClusters) {
- this._generateInitialClusters();
- }
- for (i = 0, l = this._needsRemoving.length; i < l; i++) {
- layer = this._needsRemoving[i];
- this._removeLayer(layer, true);
- }
- this._needsRemoving = [];
- for (i = 0, l = this._needsClustering.length; i < l; i++) {
- layer = this._needsClustering[i];
- //If the layer doesn't have a getLatLng then we can't cluster it, so add it to our child featureGroup
- if (!layer.getLatLng) {
- this._featureGroup.addLayer(layer);
- continue;
- }
- if (layer.__parent) {
- continue;
- }
- this._addLayer(layer, this._maxZoom);
- }
- this._needsClustering = [];
- this._map.on('zoomend', this._zoomEnd, this);
- this._map.on('moveend', this._moveEnd, this);
- if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
- this._spiderfierOnAdd();
- }
- this._bindEvents();
- //Actually add our markers to the map:
- //Remember the current zoom level and bounds
- this._zoom = this._map.getZoom();
- this._currentShownBounds = this._getExpandedVisibleBounds();
- //Make things appear on the map
- this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
- },
- //Overrides FeatureGroup.onRemove
- onRemove: function (map) {
- map.off('zoomend', this._zoomEnd, this);
- map.off('moveend', this._moveEnd, this);
- this._unbindEvents();
- //In case we are in a cluster animation
- this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
- if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
- this._spiderfierOnRemove();
- }
- //Clean up all the layers we added to the map
- this._featureGroup.onRemove(map);
- this._nonPointGroup.onRemove(map);
- this._featureGroup.clearLayers();
- this._map = null;
- },
- getVisibleParent: function (marker) {
- var vMarker = marker;
- while (vMarker !== null && !vMarker._icon) {
- vMarker = vMarker.__parent;
- }
- return vMarker;
- },
- //Remove the given object from the given array
- _arraySplice: function (anArray, obj) {
- for (var i = anArray.length - 1; i >= 0; i--) {
- if (anArray[i] === obj) {
- anArray.splice(i, 1);
- return true;
- }
- }
- },
- //Internal function for removing a marker from everything.
- //dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions)
- _removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) {
- var gridClusters = this._gridClusters,
- gridUnclustered = this._gridUnclustered,
- fg = this._featureGroup,
- map = this._map;
- //Remove the marker from distance clusters it might be in
- if (removeFromDistanceGrid) {
- for (var z = this._maxZoom; z >= 0; z--) {
- if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) {
- break;
- }
- }
- }
- //Work our way up the clusters removing them as we go if required
- var cluster = marker.__parent,
- markers = cluster._markers,
- otherMarker;
- //Remove the marker from the immediate parents marker list
- this._arraySplice(markers, marker);
- while (cluster) {
- cluster._childCount--;
- if (cluster._zoom < 0) {
- //Top level, do nothing
- break;
- } else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required
- //We need to push the other marker up to the parent
- otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0];
- //Update distance grid
- gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom));
- gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom));
- //Move otherMarker up to parent
- this._arraySplice(cluster.__parent._childClusters, cluster);
- cluster.__parent._markers.push(otherMarker);
- otherMarker.__parent = cluster.__parent;
- if (cluster._icon) {
- //Cluster is currently on the map, need to put the marker on the map instead
- fg.removeLayer(cluster);
- if (!dontUpdateMap) {
- fg.addLayer(otherMarker);
- }
- }
- } else {
- cluster._recalculateBounds();
- if (!dontUpdateMap || !cluster._icon) {
- cluster._updateIcon();
- }
- }
- cluster = cluster.__parent;
- }
- delete marker.__parent;
- },
- _propagateEvent: function (e) {
- if (e.layer instanceof L.MarkerCluster) {
- e.type = 'cluster' + e.type;
- }
- this.fire(e.type, e);
- },
- //Default functionality
- _defaultIconCreateFunction: function (cluster) {
- var childCount = cluster.getChildCount();
- var c = ' marker-cluster-';
- if (childCount < 10) {
- c += 'small';
- } else if (childCount < 100) {
- c += 'medium';
- } else {
- c += 'large';
- }
- return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
- },
- _bindEvents: function () {
- var map = this._map,
- spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
- showCoverageOnHover = this.options.showCoverageOnHover,
- zoomToBoundsOnClick = this.options.zoomToBoundsOnClick;
- //Zoom on cluster click or spiderfy if we are at the lowest level
- if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
- this.on('clusterclick', this._zoomOrSpiderfy, this);
- }
- //Show convex hull (boundary) polygon on mouse over
- if (showCoverageOnHover) {
- this.on('clustermouseover', this._hideCoverage, this);
- this.on('clustermouseout', this._hideCoverage, this);
- map.on('zoomend', this._hideCoverage, this);
- map.on('layerremove', this._hideCoverageOnRemove, this);
- }
- },
- _zoomOrSpiderfy: function (e) {
- var map = this._map;
- if (map.getMaxZoom() === map.getZoom()) {
- if (this.options.spiderfyOnMaxZoom) {
- e.layer.spiderfy();
- }
- } else if (this.options.zoomToBoundsOnClick) {
- e.layer.zoomToBounds();
- }
- },
- _showCoverage: function (e) {
- var map = this._map;
- if (this._inZoomAnimation) {
- return;
- }
- if (this._shownPolygon) {
- map.removeLayer(this._shownPolygon);
- }
- if (e.layer.getChildCount() > 2 && e.layer !== this._spiderfied) {
- this._shownPolygon = new L.Polygon(e.layer.getConvexHull(), this.options.polygonOptions);
- map.addLayer(this._shownPolygon);
- }
- },
- _hideCoverage: function () {
- if (this._shownPolygon) {
- this._map.removeLayer(this._shownPolygon);
- this._shownPolygon = null;
- }
- },
- _hideCoverageOnRemove: function (e) {
- if (e.layer === this) {
- this._hideCoverage();
- }
- },
- _unbindEvents: function () {
- var spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
- showCoverageOnHover = this.options.showCoverageOnHover,
- zoomToBoundsOnClick = this.options.zoomToBoundsOnClick,
- map = this._map;
- if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
- this.off('clusterclick', this._zoomOrSpiderfy, this);
- }
- if (showCoverageOnHover) {
- this.off('clustermouseover', this._showCoverage, this);
- this.off('clustermouseout', this._hideCoverage, this);
- map.off('zoomend', this._hideCoverage, this);
- map.off('layerremove', this._hideCoverageOnRemove, this);
- }
- },
- _zoomEnd: function () {
- if (!this._map) { //May have been removed from the map by a zoomEnd handler
- return;
- }
- this._mergeSplitClusters();
- this._zoom = this._map._zoom;
- this._currentShownBounds = this._getExpandedVisibleBounds();
- },
- _moveEnd: function () {
- if (this._inZoomAnimation) {
- return;
- }
- var newBounds = this._getExpandedVisibleBounds();
- this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, newBounds);
- this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, newBounds);
- this._currentShownBounds = newBounds;
- return;
- },
- _generateInitialClusters: function () {
- var maxZoom = this._map.getMaxZoom(),
- radius = this.options.maxClusterRadius;
- if (this.options.disableClusteringAtZoom) {
- maxZoom = this.options.disableClusteringAtZoom - 1;
- }
- this._maxZoom = maxZoom;
- this._gridClusters = {};
- this._gridUnclustered = {};
- //Set up DistanceGrids for each zoom
- for (var zoom = maxZoom; zoom >= 0; zoom--) {
- this._gridClusters[zoom] = new L.DistanceGrid(radius);
- this._gridUnclustered[zoom] = new L.DistanceGrid(radius);
- }
- this._topClusterLevel = new L.MarkerCluster(this, -1);
- },
- //Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom)
- _addLayer: function (layer, zoom) {
- var gridClusters = this._gridClusters,
- gridUnclustered = this._gridUnclustered,
- markerPoint, z;
- if (this.options.singleMarkerMode) {
- layer.options.icon = this.options.iconCreateFunction({
- getChildCount: function () {
- return 1;
- },
- getAllChildMarkers: function () {
- return [layer];
- }
- });
- }
- //Find the lowest zoom level to slot this one in
- for (; zoom >= 0; zoom--) {
- markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position
- //Try find a cluster close by
- var closest = gridClusters[zoom].getNearObject(markerPoint);
- if (closest) {
- closest._addChild(layer);
- layer.__parent = closest;
- return;
- }
- //Try find a marker close by to form a new cluster with
- closest = gridUnclustered[zoom].getNearObject(markerPoint);
- if (closest) {
- var parent = closest.__parent;
- if (parent) {
- this._removeLayer(closest, false);
- }
- //Create new cluster with these 2 in it
- var newCluster = new L.MarkerCluster(this, zoom, closest, layer);
- gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom));
- closest.__parent = newCluster;
- layer.__parent = newCluster;
- //First create any new intermediate parent clusters that don't exist
- var lastParent = newCluster;
- for (z = zoom - 1; z > parent._zoom; z--) {
- lastParent = new L.MarkerCluster(this, z, lastParent);
- gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z));
- }
- parent._addChild(lastParent);
- //Remove closest from this zoom level and any above that it is in, replace with newCluster
- for (z = zoom; z >= 0; z--) {
- if (!gridUnclustered[z].removeObject(closest, this._map.project(closest.getLatLng(), z))) {
- break;
- }
- }
- return;
- }
- //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards
- gridUnclustered[zoom].addObject(layer, markerPoint);
- }
- //Didn't get in anything, add us to the top
- this._topClusterLevel._addChild(layer);
- layer.__parent = this._topClusterLevel;
- return;
- },
- //Merge and split any existing clusters that are too big or small
- _mergeSplitClusters: function () {
- if (this._zoom < this._map._zoom) { //Zoom in, split
- this._animationStart();
- //Remove clusters now off screen
- this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, this._getExpandedVisibleBounds());
- this._animationZoomIn(this._zoom, this._map._zoom);
- } else if (this._zoom > this._map._zoom) { //Zoom out, merge
- this._animationStart();
- this._animationZoomOut(this._zoom, this._map._zoom);
- } else {
- this._moveEnd();
- }
- },
- //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)
- _getExpandedVisibleBounds: function () {
- if (!this.options.removeOutsideVisibleBounds) {
- return this.getBounds();
- }
- var map = this._map,
- bounds = map.getBounds(),
- sw = bounds._southWest,
- ne = bounds._northEast,
- latDiff = L.Browser.mobile ? 0 : Math.abs(sw.lat - ne.lat),
- lngDiff = L.Browser.mobile ? 0 : Math.abs(sw.lng - ne.lng);
- return new L.LatLngBounds(
- new L.LatLng(sw.lat - latDiff, sw.lng - lngDiff, true),
- new L.LatLng(ne.lat + latDiff, ne.lng + lngDiff, true));
- },
- //Shared animation code
- _animationAddLayerNonAnimated: function (layer, newCluster) {
- if (newCluster === layer) {
- this._featureGroup.addLayer(layer);
- } else if (newCluster._childCount === 2) {
- newCluster._addToMap();
- var markers = newCluster.getAllChildMarkers();
- this._featureGroup.removeLayer(markers[0]);
- this._featureGroup.removeLayer(markers[1]);
- } else {
- newCluster._updateIcon();
- }
- }
- });
- L.MarkerClusterGroup.include(!L.DomUtil.TRANSITION ? {
- //Non Animated versions of everything
- _animationStart: function () {
- //Do nothing...
- },
- _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
- this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
- this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
- },
- _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
- this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
- this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
- },
- _animationAddLayer: function (layer, newCluster) {
- this._animationAddLayerNonAnimated(layer, newCluster);
- }
- } : {
- //Animated versions here
- _animationStart: function () {
- this._map._mapPane.className += ' leaflet-cluster-anim';
- this._inZoomAnimation++;
- },
- _animationEnd: function () {
- if (this._map) {
- this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
- }
- this._inZoomAnimation--;
- this.fire('animationend');
- },
- _animationZoomIn: function (previousZoomLevel, newZoomLevel) {
- var me = this,
- bounds = this._getExpandedVisibleBounds(),
- fg = this._featureGroup,
- i;
- //Add all children of current clusters to map and remove those clusters from map
- this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
- var startPos = c._latlng,
- markers = c._markers,
- m;
- if (!bounds.contains(startPos)) {
- startPos = null;
- }
- if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us
- fg.removeLayer(c);
- c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds);
- } else {
- //Fade out old cluster
- c.setOpacity(0);
- c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds);
- }
- //Remove all markers that aren't visible any more
- //TODO: Do we actually need to do this on the higher levels too?
- for (i = markers.length - 1; i >= 0; i--) {
- m = markers[i];
- if (!bounds.contains(m._latlng)) {
- fg.removeLayer(m);
- }
- }
- });
- this._forceLayout();
- //Update opacities
- me._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel);
- //TODO Maybe? Update markers in _recursivelyBecomeVisible
- fg.eachLayer(function (n) {
- if (!(n instanceof L.MarkerCluster) && n._icon) {
- n.setOpacity(1);
- }
- });
- //update the positions of the just added clusters/markers
- me._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) {
- c._recursivelyRestoreChildPositions(newZoomLevel);
- });
- //Remove the old clusters and close the zoom animation
- setTimeout(function () {
- //update the positions of the just added clusters/markers
- me._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
- fg.removeLayer(c);
- c.setOpacity(1);
- });
- me._animationEnd();
- }, 200);
- },
- _animationZoomOut: function (previousZoomLevel, newZoomLevel) {
- this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel);
- //Need to add markers for those that weren't on the map before but are now
- this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
- //Remove markers that were on the map before but won't be now
- this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel, this._getExpandedVisibleBounds());
- },
- _animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) {
- var bounds = this._getExpandedVisibleBounds();
- //Animate all of the markers in the clusters to move to their cluster center point
- cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, previousZoomLevel + 1, newZoomLevel);
- var me = this;
- //Update the opacity (If we immediately set it they won't animate)
- this._forceLayout();
- cluster._recursivelyBecomeVisible(bounds, newZoomLevel);
- //TODO: Maybe use the transition timing stuff to make this more reliable
- //When the animations are done, tidy up
- setTimeout(function () {
- //This cluster stopped being a cluster before the timeout fired
- if (cluster._childCount === 1) {
- var m = cluster._markers[0];
- //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
- m.setLatLng(m.getLatLng());
- m.setOpacity(1);
- } else {
- cluster._recursively(bounds, newZoomLevel, 0, function (c) {
- c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel + 1);
- });
- }
- me._animationEnd();
- }, 200);
- },
- _animationAddLayer: function (layer, newCluster) {
- var me = this,
- fg = this._featureGroup;
- fg.addLayer(layer);
- if (newCluster !== layer) {
- if (newCluster._childCount > 2) { //Was already a cluster
- newCluster._updateIcon();
- this._forceLayout();
- this._animationStart();
- layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng()));
- layer.setOpacity(0);
- setTimeout(function () {
- fg.removeLayer(layer);
- layer.setOpacity(1);
- me._animationEnd();
- }, 200);
- } else { //Just became a cluster
- this._forceLayout();
- me._animationStart();
- me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._map.getZoom());
- }
- }
- },
- //Force a browser layout of stuff in the map
- // Should apply the current opacity and location to all elements so we can update them again for an animation
- _forceLayout: function () {
- //In my testing this works, infact offsetWidth of any element seems to work.
- //Could loop all this._layers and do this for each _icon if it stops working
- L.Util.falseFn(document.body.offsetWidth);
- }
- });
- L.markerClusterGroup = function (options) {
- return new L.MarkerClusterGroup(options);
- };
- L.MarkerCluster = L.Marker.extend({
- initialize: function (group, zoom, a, b) {
- L.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new L.LatLng(0, 0), { icon: this });
- this._group = group;
- this._zoom = zoom;
- this._markers = [];
- this._childClusters = [];
- this._childCount = 0;
- this._iconNeedsUpdate = true;
- this._bounds = new L.LatLngBounds();
- if (a) {
- this._addChild(a);
- }
- if (b) {
- this._addChild(b);
- }
- },
- //Recursively retrieve all child markers of this cluster
- getAllChildMarkers: function (storageArray) {
- storageArray = storageArray || [];
- for (var i = this._childClusters.length - 1; i >= 0; i--) {
- this._childClusters[i].getAllChildMarkers(storageArray);
- }
- for (var j = this._markers.length - 1; j >= 0; j--) {
- storageArray.push(this._markers[j]);
- }
- return storageArray;
- },
- //Returns the count of how many child markers we have
- getChildCount: function () {
- return this._childCount;
- },
- //Zoom to the extents of this cluster
- zoomToBounds: function () {
- this._group._map.fitBounds(this._bounds);
- },
- getBounds: function () {
- var bounds = new L.LatLngBounds();
- bounds.extend(this._bounds);
- return bounds;
- },
- _updateIcon: function () {
- this._iconNeedsUpdate = true;
- if (this._icon) {
- this.setIcon(this);
- }
- },
- //Cludge for Icon, we pretend to be an icon for performance
- createIcon: function () {
- if (this._iconNeedsUpdate) {
- this._iconObj = this._group.options.iconCreateFunction(this);
- this._iconNeedsUpdate = false;
- }
- return this._iconObj.createIcon();
- },
- createShadow: function () {
- return this._iconObj.createShadow();
- },
- _addChild: function (new1, isNotificationFromChild) {
- this._iconNeedsUpdate = true;
- this._expandBounds(new1);
- if (new1 instanceof L.MarkerCluster) {
- if (!isNotificationFromChild) {
- this._childClusters.push(new1);
- new1.__parent = this;
- }
- this._childCount += new1._childCount;
- } else {
- if (!isNotificationFromChild) {
- this._markers.push(new1);
- }
- this._childCount++;
- }
- if (this.__parent) {
- this.__parent._addChild(new1, true);
- }
- },
- //Expand our bounds and tell our parent to
- _expandBounds: function (marker) {
- var addedCount,
- addedLatLng = marker._wLatLng || marker._latlng;
- if (marker instanceof L.MarkerCluster) {
- this._bounds.extend(marker._bounds);
- addedCount = marker._childCount;
- } else {
- this._bounds.extend(addedLatLng);
- addedCount = 1;
- }
- if (!this._cLatLng) {
- // when clustering, take position of the first point as the cluster center
- this._cLatLng = marker._cLatLng || addedLatLng;
- }
- // when showing clusters, take weighted average of all points as cluster center
- var totalCount = this._childCount + addedCount;
- //Calculate weighted latlng for display
- if (!this._wLatLng) {
- this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng);
- } else {
- this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount;
- this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount;
- }
- },
- //Set our markers position as given and add it to the map
- _addToMap: function (startPos) {
- if (startPos) {
- this._backupLatlng = this._latlng;
- this.setLatLng(startPos);
- }
- this._group._featureGroup.addLayer(this);
- },
- _recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) {
- this._recursively(bounds, 0, maxZoom - 1,
- function (c) {
- var markers = c._markers,
- i, m;
- for (i = markers.length - 1; i >= 0; i--) {
- m = markers[i];
- //Only do it if the icon is still on the map
- if (m._icon) {
- m._setPos(center);
- m.setOpacity(0);
- }
- }
- },
- function (c) {
- var childClusters = c._childClusters,
- j, cm;
- for (j = childClusters.length - 1; j >= 0; j--) {
- cm = childClusters[j];
- if (cm._icon) {
- cm._setPos(center);
- cm.setOpacity(0);
- }
- }
- }
- );
- },
- _recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, previousZoomLevel, newZoomLevel) {
- this._recursively(bounds, newZoomLevel, 0,
- function (c) {
- c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel);
- //TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be.
- //As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate
- if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) {
- c.setOpacity(1);
- c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds
- } else {
- c.setOpacity(0);
- }
- c._addToMap();
- }
- );
- },
- _recursivelyBecomeVisible: function (bounds, zoomLevel) {
- this._recursively(bounds, 0, zoomLevel, null, function (c) {
- c.setOpacity(1);
- });
- },
- _recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) {
- this._recursively(bounds, -1, zoomLevel,
- function (c) {
- if (zoomLevel === c._zoom) {
- return;
- }
- //Add our child markers at startPos (so they can be animated out)
- for (var i = c._markers.length - 1; i >= 0; i--) {
- var nm = c._markers[i];
- if (!bounds.contains(nm._latlng)) {
- continue;
- }
- if (startPos) {
- nm._backupLatlng = nm.getLatLng();
- nm.setLatLng(startPos);
- if (nm.setOpacity) {
- nm.setOpacity(0);
- }
- }
- c._group._featureGroup.addLayer(nm);
- }
- },
- function (c) {
- c._addToMap(startPos);
- }
- );
- },
- _recursivelyRestoreChildPositions: function (zoomLevel) {
- //Fix positions of child markers
- for (var i = this._markers.length - 1; i >= 0; i--) {
- var nm = this._markers[i];
- if (nm._backupLatlng) {
- nm.setLatLng(nm._backupLatlng);
- delete nm._backupLatlng;
- }
- }
- if (zoomLevel - 1 === this._zoom) {
- //Reposition child clusters
- for (var j = this._childClusters.length - 1; j >= 0; j--) {
- this._childClusters[j]._restorePosition();
- }
- } else {
- for (var k = this._childClusters.length - 1; k >= 0; k--) {
- this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel);
- }
- }
- },
- _restorePosition: function () {
- if (this._backupLatlng) {
- this.setLatLng(this._backupLatlng);
- delete this._backupLatlng;
- }
- },
- //exceptBounds: If set, don't remove any markers/clusters in it
- _recursivelyRemoveChildrenFromMap: function (previousBounds, zoomLevel, exceptBounds) {
- var m, i;
- this._recursively(previousBounds, -1, zoomLevel - 1,
- function (c) {
- //Remove markers at every level
- for (i = c._markers.length - 1; i >= 0; i--) {
- m = c._markers[i];
- if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
- c._group._featureGroup.removeLayer(m);
- if (m.setOpacity) {
- m.setOpacity(1);
- }
- }
- }
- },
- function (c) {
- //Remove child clusters at just the bottom level
- for (i = c._childClusters.length - 1; i >= 0; i--) {
- m = c._childClusters[i];
- if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
- c._group._featureGroup.removeLayer(m);
- if (m.setOpacity) {
- m.setOpacity(1);
- }
- }
- }
- }
- );
- },
- //Run the given functions recursively to this and child clusters
- // boundsToApplyTo: a L.LatLngBounds representing the bounds of what clusters to recurse in to
- // zoomLevelToStart: zoom level to start running functions (inclusive)
- // zoomLevelToStop: zoom level to stop running functions (inclusive)
- // runAtEveryLevel: function that takes an L.MarkerCluster as an argument that should be applied on every level
- // runAtBottomLevel: function that takes an L.MarkerCluster as an argument that should be applied at only the bottom level
- _recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) {
- var childClusters = this._childClusters,
- zoom = this._zoom,
- i, c;
- if (zoomLevelToStart > zoom) { //Still going down to required depth, just recurse to child clusters
- for (i = childClusters.length - 1; i >= 0; i--) {
- c = childClusters[i];
- if (boundsToApplyTo.intersects(c._bounds)) {
- c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
- }
- }
- } else { //In required depth
- if (runAtEveryLevel) {
- runAtEveryLevel(this);
- }
- if (runAtBottomLevel && this._zoom === zoomLevelToStop) {
- runAtBottomLevel(this);
- }
- //TODO: This loop is almost the same as above
- if (zoomLevelToStop > zoom) {
- for (i = childClusters.length - 1; i >= 0; i--) {
- c = childClusters[i];
- if (boundsToApplyTo.intersects(c._bounds)) {
- c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
- }
- }
- }
- }
- },
- _recalculateBounds: function () {
- var markers = this._markers,
- childClusters = this._childClusters,
- i;
- this._bounds = new L.LatLngBounds();
- delete this._wLatLng;
- for (i = markers.length - 1; i >= 0; i--) {
- this._expandBounds(markers[i]);
- }
- for (i = childClusters.length - 1; i >= 0; i--) {
- this._expandBounds(childClusters[i]);
- }
- },
- //Returns true if we are the parent of only one cluster and that cluster is the same as us
- _isSingleParent: function () {
- //Don't need to check this._markers as the rest won't work if there are any
- return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount;
- }
- });
- L.DistanceGrid = function (cellSize) {
- this._cellSize = cellSize;
- this._sqCellSize = cellSize * cellSize;
- this._grid = {};
- this._objectPoint = { };
- };
- L.DistanceGrid.prototype = {
- addObject: function (obj, point) {
- var x = this._getCoord(point.x),
- y = this._getCoord(point.y),
- grid = this._grid,
- row = grid[y] = grid[y] || {},
- cell = row[x] = row[x] || [],
- stamp = L.Util.stamp(obj);
- this._objectPoint[stamp] = point;
- cell.push(obj);
- },
- updateObject: function (obj, point) {
- this.removeObject(obj);
- this.addObject(obj, point);
- },
- //Returns true if the object was found
- removeObject: function (obj, point) {
- var x = this._getCoord(point.x),
- y = this._getCoord(point.y),
- grid = this._grid,
- row = grid[y] = grid[y] || {},
- cell = row[x] = row[x] || [],
- i, len;
- delete this._objectPoint[L.Util.stamp(obj)];
- for (i = 0, len = cell.length; i < len; i++) {
- if (cell[i] === obj) {
- cell.splice(i, 1);
- if (len === 1) {
- delete row[x];
- }
- return true;
- }
- }
- },
- eachObject: function (fn, context) {
- var i, j, k, len, row, cell, removed,
- grid = this._grid;
- for (i in grid) {
- row = grid[i];
- for (j in row) {
- cell = row[j];
- for (k = 0, len = cell.length; k < len; k++) {
- removed = fn.call(context, cell[k]);
- if (removed) {
- k--;
- len--;
- }
- }
- }
- }
- },
- getNearObject: function (point) {
- var x = this._getCoord(point.x),
- y = this._getCoord(point.y),
- i, j, k, row, cell, len, obj, dist,
- objectPoint = this._objectPoint,
- closestDistSq = this._sqCellSize,
- closest = null;
- for (i = y - 1; i <= y + 1; i++) {
- row = this._grid[i];
- if (row) {
- for (j = x - 1; j <= x + 1; j++) {
- cell = row[j];
- if (cell) {
- for (k = 0, len = cell.length; k < len; k++) {
- obj = cell[k];
- dist = this._sqDist(objectPoint[L.Util.stamp(obj)], point);
- if (dist < closestDistSq) {
- closestDistSq = dist;
- closest = obj;
- }
- }
- }
- }
- }
- }
- return closest;
- },
- _getCoord: function (x) {
- return Math.floor(x / this._cellSize);
- },
- _sqDist: function (p, p2) {
- var dx = p2.x - p.x,
- dy = p2.y - p.y;
- return dx * dx + dy * dy;
- }
- };
- /* Copyright (c) 2012 the authors listed at the following URL, and/or
- the authors of referenced articles or incorporated external code:
- http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- "Software"), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434
- */
- (function () {
- L.QuickHull = {
- getDistant: function (cpt, bl) {
- var vY = bl[1].lat - bl[0].lat,
- vX = bl[0].lng - bl[1].lng;
- return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng));
- },
- findMostDistantPointFromBaseLine: function (baseLine, latLngs) {
- var maxD = 0,
- maxPt = null,
- newPoints = [],
- i, pt, d;
- for (i = latLngs.length - 1; i >= 0; i--) {
- pt = latLngs[i];
- d = this.getDistant(pt, baseLine);
- if (d > 0) {
- newPoints.push(pt);
- } else {
- continue;
- }
- if (d > maxD) {
- maxD = d;
- maxPt = pt;
- }
- }
- return { 'maxPoint': maxPt, 'newPoints': newPoints };
- },
- buildConvexHull: function (baseLine, latLngs) {
- var convexHullBaseLines = [],
- t = this.findMostDistantPointFromBaseLine(baseLine, latLngs);
- if (t.maxPoint) { // if there is still a point "outside" the base line
- convexHullBaseLines =
- convexHullBaseLines.concat(
- this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints)
- );
- convexHullBaseLines =
- convexHullBaseLines.concat(
- this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints)
- );
- return convexHullBaseLines;
- } else { // if there is no more point "outside" the base line, the current base line is part of the convex hull
- return [baseLine];
- }
- },
- getConvexHull: function (latLngs) {
- //find first baseline
- var maxLat = false, minLat = false,
- maxPt = null, minPt = null,
- i;
- for (i = latLngs.length - 1; i >= 0; i--) {
- var pt = latLngs[i];
- if (maxLat === false || pt.lat > maxLat) {
- maxPt = pt;
- maxLat = pt.lat;
- }
- if (minLat === false || pt.lat < minLat) {
- minPt = pt;
- minLat = pt.lat;
- }
- }
- var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs),
- this.buildConvexHull([maxPt, minPt], latLngs));
- return ch;
- }
- };
- }());
- L.MarkerCluster.include({
- getConvexHull: function () {
- var childMarkers = this.getAllChildMarkers(),
- points = [],
- hullLatLng = [],
- hull, p, i;
- for (i = childMarkers.length - 1; i >= 0; i--) {
- p = childMarkers[i].getLatLng();
- points.push(p);
- }
- hull = L.QuickHull.getConvexHull(points);
- for (i = hull.length - 1; i >= 0; i--) {
- hullLatLng.push(hull[i][0]);
- }
- return hullLatLng;
- }
- });
- //This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
- //Huge thanks to jawj for implementing it first to make my job easy :-)
- L.MarkerCluster.include({
- _2PI: Math.PI * 2,
- _circleFootSeparation: 25, //related to circumference of circle
- _circleStartAngle: Math.PI / 6,
- _spiralFootSeparation: 28, //related to size of spiral (experiment!)
- _spiralLengthStart: 11,
- _spiralLengthFactor: 5,
- _circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards.
- // 0 -> always spiral; Infinity -> always circle
- spiderfy: function () {
- if (this._group._spiderfied === this || this._group._inZoomAnimation) {
- return;
- }
- var childMarkers = this.getAllChildMarkers(),
- group = this._group,
- map = group._map,
- center = map.latLngToLayerPoint(this._latlng),
- positions;
- this._group._unspiderfy();
- this._group._spiderfied = this;
- //TODO Maybe: childMarkers order by distance to center
- if (childMarkers.length >= this._circleSpiralSwitchover) {
- positions = this._generatePointsSpiral(childMarkers.length, center);
- } else {
- center.y += 10; //Otherwise circles look wrong
- positions = this._generatePointsCircle(childMarkers.length, center);
- }
- this._animationSpiderfy(childMarkers, positions);
- },
- unspiderfy: function (zoomDetails) {
- /// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param>
- if (this._group._inZoomAnimation) {
- return;
- }
- this._animationUnspiderfy(zoomDetails);
- this._group._spiderfied = null;
- },
- _generatePointsCircle: function (count, centerPt) {
- var circumference = this._group.options.spiderfyDistanceMultiplier * this._circleFootSeparation * (2 + count),
- legLength = circumference / this._2PI, //radius from circumference
- angleStep = this._2PI / count,
- res = [],
- i, angle;
- res.length = count;
- for (i = count - 1; i >= 0; i--) {
- angle = this._circleStartAngle + i * angleStep;
- res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
- }
- return res;
- },
- _generatePointsSpiral: function (count, centerPt) {
- var legLength = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthStart,
- separation = this._group.options.spiderfyDistanceMultiplier * this._spiralFootSeparation,
- lengthFactor = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthFactor,
- angle = 0,
- res = [],
- i;
- res.length = count;
- for (i = count - 1; i >= 0; i--) {
- angle += separation / legLength + i * 0.0005;
- res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
- legLength += this._2PI * lengthFactor / angle;
- }
- return res;
- },
- _noanimationUnspiderfy: function () {
- var group = this._group,
- map = group._map,
- fg = group._featureGroup,
- childMarkers = this.getAllChildMarkers(),
- m, i;
- this.setOpacity(1);
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i];
- fg.removeLayer(m);
- if (m._preSpiderfyLatlng) {
- m.setLatLng(m._preSpiderfyLatlng);
- delete m._preSpiderfyLatlng;
- }
- if (m.setZIndexOffset) {
- m.setZIndexOffset(0);
- }
- if (m._spiderLeg) {
- map.removeLayer(m._spiderLeg);
- delete m._spiderLeg;
- }
- }
- }
- });
- L.MarkerCluster.include(!L.DomUtil.TRANSITION ? {
- //Non Animated versions of everything
- _animationSpiderfy: function (childMarkers, positions) {
- var group = this._group,
- map = group._map,
- fg = group._featureGroup,
- i, m, leg, newPos;
- for (i = childMarkers.length - 1; i >= 0; i--) {
- newPos = map.layerPointToLatLng(positions[i]);
- m = childMarkers[i];
- m._preSpiderfyLatlng = m._latlng;
- m.setLatLng(newPos);
- if (m.setZIndexOffset) {
- m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
- }
- fg.addLayer(m);
- leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' });
- map.addLayer(leg);
- m._spiderLeg = leg;
- }
- this.setOpacity(0);
- group.fire('spiderfied');
- },
- _animationUnspiderfy: function () {
- this._noanimationUnspiderfy();
- }
- } : {
- //Animated versions here
- SVG_ANIMATION: (function () {
- return document.createElementNS('http://www.w3.org/2000/svg', 'animate').toString().indexOf('SVGAnimate') > -1;
- }()),
- _animationSpiderfy: function (childMarkers, positions) {
- var me = this,
- group = this._group,
- map = group._map,
- fg = group._featureGroup,
- thisLayerPos = map.latLngToLayerPoint(this._latlng),
- i, m, leg, newPos;
- //Add markers to map hidden at our center point
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i];
- //If it is a marker, add it now and we'll animate it out
- if (m.setOpacity) {
- m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
- m.setOpacity(0);
-
- fg.addLayer(m);
- m._setPos(thisLayerPos);
- } else {
- //Vectors just get immediately added
- fg.addLayer(m);
- }
- }
- group._forceLayout();
- group._animationStart();
- var initialLegOpacity = L.Path.SVG ? 0 : 0,
- xmlns = L.Path.SVG_NS;
- for (i = childMarkers.length - 1; i >= 0; i--) {
- newPos = map.layerPointToLatLng(positions[i]);
- m = childMarkers[i];
- //Move marker to new position
- m._preSpiderfyLatlng = m._latlng;
- m.setLatLng(newPos);
-
- if (m.setOpacity) {
- m.setOpacity(1);
- }
- //Add Legs.
- leg = new L.Polyline([me._latlng, newPos], { weight: 1.5, color: '#222', opacity: 0 });
- map.addLayer(leg);
- m._spiderLeg = leg;
- //Following animations don't work for canvas
- if (!L.Path.SVG || !this.SVG_ANIMATION) {
- continue;
- }
- //How this works:
- //http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios
- //http://dev.opera.com/articles/view/advanced-svg-animation-techniques/
- //Animate length
- var length = leg._path.getTotalLength();
- leg._path.setAttribute("stroke-dasharray", length + "," + length);
- var anim = document.createElementNS(xmlns, "animate");
- anim.setAttribute("attributeName", "stroke-dashoffset");
- anim.setAttribute("begin", "indefinite");
- anim.setAttribute("from", length);
- anim.setAttribute("to", 0);
- anim.setAttribute("dur", 0.25);
- leg._path.appendChild(anim);
- anim.beginElement();
- //Animate opacity
- anim = document.createElementNS(xmlns, "animate");
- anim.setAttribute("attributeName", "stroke-opacity");
- anim.setAttribute("attributeName", "stroke-opacity");
- anim.setAttribute("begin", "indefinite");
- anim.setAttribute("from", 0);
- anim.setAttribute("to", 0);
- anim.setAttribute("dur", 0.25);
- leg._path.appendChild(anim);
- anim.beginElement();
- }
- me.setOpacity(0);
- //Set the opacity of the spiderLegs back to their correct value
- // The animations above override this until they complete.
- // If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts.
- if (L.Path.SVG) {
- this._group._forceLayout();
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i]._spiderLeg;
- m.options.opacity = 0;
- m._path.setAttribute('stroke-opacity', 0);
- }
- }
- setTimeout(function () {
- group._animationEnd();
- group.fire('spiderfied');
- }, 200);
- },
- _animationUnspiderfy: function (zoomDetails) {
- var group = this._group,
- map = group._map,
- fg = group._featureGroup,
- thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng),
- childMarkers = this.getAllChildMarkers(),
- svg = L.Path.SVG && this.SVG_ANIMATION,
- m, i, a;
- group._animationStart();
- //Make us visible and bring the child markers back in
- this.setOpacity(1);
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i];
- //Marker was added to us after we were spidified
- if (!m._preSpiderfyLatlng) {
- continue;
- }
- //Fix up the location to the real one
- m.setLatLng(m._preSpiderfyLatlng);
- delete m._preSpiderfyLatlng;
- //Hack override the location to be our center
- if (m.setOpacity) {
- m._setPos(thisLayerPos);
- m.setOpacity(0);
- } else {
- fg.removeLayer(m);
- }
- //Animate the spider legs back in
- if (svg) {
- a = m._spiderLeg._path.childNodes[0];
- a.setAttribute('to', a.getAttribute('from'));
- a.setAttribute('from', 0);
- a.beginElement();
- a = m._spiderLeg._path.childNodes[1];
- a.setAttribute('from', 0);
- a.setAttribute('to', 0);
- a.setAttribute('stroke-opacity', 0);
- a.beginElement();
- m._spiderLeg._path.setAttribute('stroke-opacity', 0);
- }
- }
- setTimeout(function () {
- //If we have only <= one child left then that marker will be shown on the map so don't remove it!
- var stillThereChildCount = 0;
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i];
- if (m._spiderLeg) {
- stillThereChildCount++;
- }
- }
- for (i = childMarkers.length - 1; i >= 0; i--) {
- m = childMarkers[i];
- if (!m._spiderLeg) { //Has already been unspiderfied
- continue;
- }
- if (m.setOpacity) {
- m.setOpacity(1);
- m.setZIndexOffset(0);
- }
- if (stillThereChildCount > 1) {
- fg.removeLayer(m);
- }
- map.removeLayer(m._spiderLeg);
- delete m._spiderLeg;
- }
- group._animationEnd();
- }, 200);
- }
- });
- L.MarkerClusterGroup.include({
- //The MarkerCluster currently spiderfied (if any)
- _spiderfied: null,
- _spiderfierOnAdd: function () {
- this._map.on('click', this._unspiderfyWrapper, this);
- if (this._map.options.zoomAnimation) {
- this._map.on('zoomstart', this._unspiderfyZoomStart, this);
- } else {
- //Browsers without zoomAnimation don't fire zoomstart
- this._map.on('zoomend', this._unspiderfyWrapper, this);
- }
- if (L.Path.SVG && !L.Browser.touch) {
- this._map._initPathRoot();
- //Needs to happen in the pageload, not after, or animations don't work in webkit
- // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements
- //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable
- }
- },
- _spiderfierOnRemove: function () {
- this._map.off('click', this._unspiderfyWrapper, this);
- this._map.off('zoomstart', this._unspiderfyZoomStart, this);
- this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
- this._unspiderfy(); //Ensure that markers are back where they should be
- },
- //On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated)
- //This means we can define the animation they do rather than Markers doing an animation to their actual location
- _unspiderfyZoomStart: function () {
- if (!this._map) { //May have been removed from the map by a zoomEnd handler
- return;
- }
- this._map.on('zoomanim', this._unspiderfyZoomAnim, this);
- },
- _unspiderfyZoomAnim: function (zoomDetails) {
- //Wait until the first zoomanim after the user has finished touch-zooming before running the animation
- if (L.DomUtil.hasClass(this._map._mapPane, 'leaflet-touching')) {
- return;
- }
- this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
- this._unspiderfy(zoomDetails);
- },
- _unspiderfyWrapper: function () {
- /// <summary>_unspiderfy but passes no arguments</summary>
- this._unspiderfy();
- },
- _unspiderfy: function (zoomDetails) {
- if (this._spiderfied) {
- this._spiderfied.unspiderfy(zoomDetails);
- }
- },
- _noanimationUnspiderfy: function () {
- if (this._spiderfied) {
- this._spiderfied._noanimationUnspiderfy();
- }
- },
- //If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
- _unspiderfyLayer: function (layer) {
- if (layer._spiderLeg) {
- this._featureGroup.removeLayer(layer);
- layer.setOpacity(1);
- //Position will be fixed up immediately in _animationUnspiderfy
- layer.setZIndexOffset(0);
- this._map.removeLayer(layer._spiderLeg);
- delete layer._spiderLeg;
- }
- }
- });
- }(window, document));
|