Search code examples
gmaps4railsvisiblemarkermarkerclusterer

Updating gmaps4rails 'clusters' when hiding or showing visible markers


This javascript code hides all the markers on a google map which I initially populated using the gmaps4rails gem in a Rails 3.2 app.

var markers=Gmaps.map.markers
for(i=0;i<markers.length;i++){markers[i].serviceObject.setVisible(false); }

The issue I have is that the "clusters" still show the same counters before and after the above code is ran. I've searched around a bit and haven't figured out the write line(s) to add to update the clusters.

P.S. I'm pretty sure that "cluster" is the correct name for what I'm talking about. What I'm referring to are the counters that the map shows when you are zoomed out to a view where there isn't enough room to distinguish between individual markers and the map shows a colored, circularish icon with a count of the number of map markers in that area.


Solution

  • If you want to update your map with a different set of markers, we'll call them differentMarkers you can call

    var differentMarkers = ...
    Gmaps.map.replaceMarkers(differentMarkers);
    

    and the clusters will update.

    If you want to add markers to the existing set use

    var additionalMarkers = ...
    Gmaps.map.addMarkers(additionalMarkers);
    

    I haven't found a method to remove markers but you could call the replaceMarkers with an array that has the markers removed.

    Not sure if this is the way it is meant to be done but seems to work.


    Adding and replacing markers this way is also explained in the wiki for gmaps4rails. https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Javascript-goodies