Search code examples
javascriptgoogle-mapsmarkerclusterer

Show/hide markerclusters in Google Maps with Javascript


I've got a map with 2 types of markers and until now I provided 2 checkboxes which gave the possibility to show/hide those markers with this code:

Checkboxes

<input type="checkbox" id="suggested" name="suggested" onclick="toggleMarkers('suggested')">
<label for="suggested"> Suggested</label>
<input type="checkbox" id="organized" name="organized" onclick="toggleMarkers('organized')">
<label for="organized"> Organized</label>

Javascript

function toggleMarkers(type) {
    switch(type)
    {
        case 'suggested':
            for (var i = 0; i < suggested.length; i++) {
                if (suggested[i].getMap() === null) {
                    suggested[i].setMap(map);
                } else {
                    suggested[i].setMap(null);
                }
            }
            break;

        case 'organized':
            for (var i = 0; i < organized.length; i++) {
                if (organized[i].getMap() === null) {
                    organized[i].setMap(map);
                } else {
                    organized[i].setMap(null);
                }
            }
            break;

        default: break;
    }
}

where suggested and organized are the 2 arrays containing the markers of the corresponding type. Now I've noticed that with many markers that is not enough and the map can be confusing, then I've decided to introduce the markercluster. I could do so, it was enough to import the library and to add

let suggestedCluster = new MarkerClusterer(map, suggested, {gridSize:80, styles:styles[0]});

let organizedCluster = new MarkerClusterer(map, organized, {gridSize:80, styles:styles[1]});

The problem is that I want to leave the functionality to show/hide a category of markers, but the code above is no more good for that, it has a wrong behaviour. How could I show/hide a category of clusters and also the markers of the same category which are not included inside a cluster?


Solution

  • According to the reference, MarkerClusterer has methods addMarkers and clearMarkers.

    function toggleClusterer(type){
        switch(type)
        {
            case 'suggested':
                toggle(suggestedCluster, suggested);
                break;
    
            case 'organized':
                toggle(organizedCluster, organized);
                break;
        }
    
        function toggle(clusterer, markers) {
            if(clusterer.getMarkers().length == 0){
                clusterer.addMarkers(markers);
            } else {
                clusterer.clearMarkers();
            }
        }
    }