Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide a MarkerCluster in google maps v3?

I need to have different markers for different mapTypes, and I'm pushing them to a MarkerClusterer.

I "hide" the markers with:

cluster.set("map", null);
cluster.resetViewport();
cluster.redraw();

And "show" them with:

cluster.set("map", MAP);
cluster.resetViewport();
cluster.redraw();

The problem is that MarkerClusterer seems to not like set("map", null); it throws the error TypeError: Object #<a MarkerClusterer> has no method 'remove'. How can I show/hide them the proper way?

like image 572
Gabi Purcaru Avatar asked Oct 30 '10 19:10

Gabi Purcaru


3 Answers

In the Javascript API v3 it is sufficient to say:

clusterer.setMap(null);

If you set your map back to the existing map object, the clusters will reappear.

clusterer.setMap( this.map );

Also, I would suggest not to name your Clusterer 'cluster', like in your example. The MarkerClusterer contains Cluster objects, which are the actual clustered markers and not the ClusterER itself.

like image 67
Micros Avatar answered Oct 24 '22 06:10

Micros


Elegant way to clear the cluster

cluster.clearMarkers();
like image 25
code-jaff Avatar answered Oct 24 '22 08:10

code-jaff


Here is a more complete solution:

in .html add:

<div id="map-canvas-hidden" style="display:none"></div>
<div id="map-canvas-shown" style="width:500px; height:500px"></div>

in .js add:

MarkerClusterer.prototype.remove = function() { };
var HIDDEN_MAP = new google.maps.Map(document.getElementById("map-canvas-hidden"), {});
var gmap = new google.maps.Map(document.getElementById("map-canvas-shown"), {});

to show the clusters:

    cluster.setMap(gmap);
    cluster.resetViewport();
    cluster.redraw();

to hide the clusters:

    cluster.setMap(HIDDEN_MAP);
    cluster.resetViewport();
    cluster.redraw();

finally, I needed the folowing patches to markerclusterer.js:

--- markerclusterer.js.orig 2013-12-06 18:02:32.887516000 +0100
+++ markerclusterer.js  2013-12-06 18:03:25.487516924 +0100
@@ -620,6 +620,7 @@
  */
 MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
   var projection = this.getProjection();
+  if (!projection) return null;

   // Turn the bounds into latlng.
   var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
@@ -657,7 +658,7 @@
  * @private
  */
 MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
-  return bounds.contains(marker.getPosition());
+  return bounds ? bounds.contains(marker.getPosition()) : false;
 };

hope this helps

like image 35
Maurix Avatar answered Oct 24 '22 08:10

Maurix