From f693a49dec0236ab576a3e68acda36386f074df5 Mon Sep 17 00:00:00 2001 From: danzel Date: Wed, 13 Nov 2013 15:26:41 +1300 Subject: [PATCH] Change zoomToBounds to only zoom in as far as it needs to to show all child markers. Fixes #185 --- README.md | 1 + src/MarkerCluster.js | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 612e741ff..4a4dfa78c 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ markers.on('clusterclick', function (a) { ### Zooming to the bounds of a cluster When you recieve an event from a cluster you can zoom to its bounds in one easy step. +If all of the markers will appear at a higher zoom level, that zoom level is zoomed to instead. See [marker-clustering-zoomtobounds.html](http://leaflet.github.com/Leaflet.markercluster/example/marker-clustering-zoomtobounds.html) for a working example. ```javascript markers.on('clusterclick', function (a) { diff --git a/src/MarkerCluster.js b/src/MarkerCluster.js index 628896301..0663c47a6 100644 --- a/src/MarkerCluster.js +++ b/src/MarkerCluster.js @@ -42,9 +42,28 @@ L.MarkerCluster = L.Marker.extend({ return this._childCount; }, - //Zoom to the extents of this cluster + //Zoom to the minimum of showing all of the child markers, or the extents of this cluster zoomToBounds: function () { - this._group._map.fitBounds(this._bounds); + var childClusters = this._childClusters.slice(), + map = this._group._map, + boundsZoom = map.getBoundsZoom(this._bounds), + zoom = this._zoom + 1, + i; + + while (childClusters.length > 0 && boundsZoom > zoom) { + zoom++; + var newClusters = []; + for (i = 0; i < childClusters.length; i++) { + newClusters = newClusters.concat(childClusters[i]._childClusters); + } + childClusters = newClusters; + } + + if (boundsZoom > zoom) { + this._group._map.setView(this._latlng, zoom); + } else { + this._group._map.fitBounds(this._bounds); + } }, getBounds: function () {