How to hide and show MarkerClusterer in google maps

梦想与她 提交于 2019-11-30 07:18:04
nicoabie

I've been struggling the whole morning with this but fortunately I got to a solution.

First of all, make sure you have the latest MarkerClustererPlus version https://github.com/googlemaps/js-marker-clusterer

then it is very easy,

When creating the markers make sure you

set its visible flag to false.

And when creating the marker clusterer do it this way:

new MarkerClusterer(map, markers, { ignoreHidden: true });

if you want to show the clusterer just do this:

for (var it in markers) {
    markers[it].setVisible(true);
}

markerCluster.repaint();

to hide the cluster:

for (var it in markers) {
    markers[it].setVisible(false);
}

markerCluster.repaint();

Hope it helps, regards

red_alert

You can, for example:

  1. Define the click handlers for the buttons;
  2. Using the function getMarkers() to get all the markers and save the results to a variable (var allMarkers = getMarkers());
  3. Create another variable to add/remove markers (var currentMarkers = allMarkers);
  4. When you click in each button you can loop the currentMarkers variable and use the functions removeMarker(MARKER_TO_REMOVE) or addMarker(MARKER_TO_ADD, true) (the true is to redraw the map);
  5. When you are looping the markers you can access their information (do a console.log(marker) to see what I'm talking about);

For more information you could see the documentation here: https://googlemaps.github.io/js-marker-clusterer/docs/reference.html

I have the same case and this is how I do it... hope it helps

cluster instanciate

let markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});

to hide the clusters:

function hideMarkers() {
    for (let i in markers) {
        markers[i].setMap(null);
    }
    markerCluster.clearMarkers();
}

to show the clusters:

function showMarkers() {
    for (let i in markers) {
        markers[i].setMap(map);
    }
    markerCluster.addMarkers(markers);
}

here is a jsfiddle link to test http://jsfiddle.net/3s6qfzcy/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!