0

I use @googlemaps/markerclusterer to cluster markers on Google map, which integrated in a Reactjs app.

In a hook I iterate through addresses, create markers and markersClusterer:

  useEffect(() => {
    const markers = addresses.map((address) => {
      new window.google.maps.Marker({
        position: {
          lat: address.attributes.lat,
          lng: address.attributes.lng,
        },
        map: map,
      });
    });

    new MarkerClusterer({ map, markers });
  }, [addresses, map, mapParams]);

In the mapParams I store map bounds - this dependecy help to rerender markers if bounds changed. When I use zoom on the map I would see proper clustering depends on the zoom level. Instead of that I see clusters for different zoom levels. before zoom after zoom

Alexey Zalyotov
  • 326
  • 2
  • 5
  • 16

1 Answers1

0

Okay, I found the problem. Look's like I have to clear markers from clusterer during every rerender. Updated hook code:

let markerClusterer: MarkerClusterer | null = null;
let markers: google.maps.Marker[] = [];

useEffect(() => {
  markerClusterer?.clearMarkers();
  markers.forEach((marker) => marker.setMap(null));

  const markers = addresses.map((address) => {
    new window.google.maps.Marker({
      position: {
        lat: address.attributes.lat,
        lng: address.attributes.lng,
      },
      map: map,
    });
  });

  new MarkerClusterer({ map, markers });
}, [addresses, map, mapParams]);

Thank Piero Alberto for the clue in his question

Alexey Zalyotov
  • 326
  • 2
  • 5
  • 16