How to Clear Marker Clustering for Google Maps?

What I’m trying to do:
I am adding markers based on the user setting a range and displaying only data points within that range.

What I’ve tried and what’s not working:
I can add the markers with the MarkerClusterer, but when I recreate a list, it seems to keep the existing markers and adds the new ones instead of creating the clustering from scratch. In a way it makes sense, since the clusterer takes the map (with existing markers added) as an argument, but is there a way to either reset the map (removing all markers) or use a clearMarkers or some such method on the MarkerClusterer?

Code Sample:

    markers_list = [({"lat":x["Lat"],"lng":x["Lng"]},x["SiteLabel"]) for x in my_data_dict]
    self.markers = [GoogleMap.Marker(position=p, label=l) for p, l in markers_list]
    
    MarkerClusterer({"markers": self.markers, "map": self.map_1})

I think you need to add self.map_1.clear() in the MarkerClusterer or before running it to remove the existing markers. It seems that markers are basically like components within the container of the map.

I tried that too, but it does not seem to do anything?

Can you drop a clone link? Maybe I was looking at different markers, but when I used that removed the markers I added.

Here is a clone link that illustrates the problem:

Expected behavior: when the user selects a different group and clicks the button, the new selection should be shown on the map instaed of the previous one; however, that does not happen. And clearing the map does not seem to help?

Am I missing something obvious?

So, the reason map_1.clear() doesn’t work is that the markers were added with the 3rd-party JS library. As such, you need to use the specific marker clusterer that added those markers to clear it:

def __init__(self, **properties):
    self.marker_clusterer = None

def update_sites(self, **event_args):
    if self.marker_clusterer:
      self.marker_clusterer.clearMarkers()
    self.marker_clusterer = MarkerClusterer({"markers": self.markers, "map": self.map_1})
2 Likes

Thanks, it worked. I was following the example from another post. but I guess in that case there was not a need to reset the markers so it was omitted there.

1 Like