Zoom all the way in to a marker cluster with markerclusterer.js

/ Published in: JavaScript
Save to your folder(s)

[MarkerClusterer](http://googlegeodevelopers.blogspot.com/2009/04/markerclusterer-solution-to-too-many.html) is an awesome marker clustering utility for the Google Maps API. Currently when you click on a cluster, the map is re-centered and zooms in one level. This is sometimes a problem if your markers are very close together and the map is zoomed very far out. It take a few clicks before the markers become unclustered.

This snippet modifies the clusterclick behavior, so that clicking on a cluster zooms in more intelligently. Instead of simply zooming in one level, the bounds of the map are redefined based on the lat/long of the markers that a cluster contains.

Make sure you are using the [dev branch of MarkerClusterer](http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/1.0/src/markerclusterer.js), earlier versions do not allow you to override the default clusterclick behavior.

Be sure to set `zoomOnClick: false`.

Also, this script make's use of [jQuery's $.each() function](http://api.jquery.com/jQuery.each/). If you aren't using jQuery, you should find a different way to iterate through the loop.

Copy this code and paste it in your HTML
  1. GEvent.addListener(markerCluster, "clusterclick", function (cluster) {
  2. var markers = cluster.getMarkers();
  3. var bounds = new GLatLngBounds();
  4. $.each(markers, function(i, marker){
  5. bounds.extend(marker.marker.getLatLng());
  6. });
  7. map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
  8. });

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.