Show/hide Google 地图中的标记簇 Javascript

Show/hide markerclusters in Google Maps with Javascript

我有一张带有 2 种类型标记的地图,直到现在我提供了 2 个复选框,这使得 show/hide 这些标记有可能使用以下代码:

复选框

<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;
    }
}

其中 suggestedorganized 是包含相应类型标记的 2 个数组。现在我注意到有很多标记是不够的,地图可能会很混乱,然后我决定引入 markercluster。我可以这样做,导入库并添加

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

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

问题是我想将功能留给 show/hide 一类标记,但上面的代码对此不再有用,它有错误的行为。我怎么能show/hide一个簇的类别以及不包含在簇内的同一类别的标记?

根据 the referenceMarkerClusterer 有方法 addMarkersclearMarkers

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();
        }
    }
}