google-mapsgoogle-maps-api-3google-maps-reactreact-google-maps-api

Infowindow on Marker Cluster - @react-google-maps


Is there any way to show an Info Window on a marker cluster in @react-google-maps, we have displayed an info window on a single marker which works absolutely fine but didn't find a way to display the same for a marker cluster.

enter image description here

What have I already tried?

I have tried to add an info window like an inner component inside the marker cluster

<GoogleMap setMap={setMap}>
  <MarkerClustererF onMouseOver={(ele)=>{setMarkerClusterTitle(ele);}}>
    {clusterer =>
    locs.map((loc: any) => (
    <>
      <CustomMarker position={loc} clusterer={clusterer} nodeData={loc.nodeData}
        primaryKeyColumnName={props.selectedTableInfo.pkColumnName} setNodeData={setCurrentMapNodeData}
        handleMapInfoWindowOpenClose={handleMapInfoWindowOpenClose} />
      <InfoWindow position={loc}>
        <div><strong>API : </strong>Working</div>
      </InfoWindow>
    </>
    ))
    }
  </MarkerClustererF>
</GoogleMap>

But this doesn't work for clusters this will just add an info window for all the markers, what we need is an info window on clusters that pops up on hover.


Solution

  • First, you need to create infoWindow instance in your Component, and Open and Close in onMouseOver, onMouseOut event handler.

    const GoogleMapContainer = () => {
      const infoWindow = new google.maps.InfoWindow();
      .....
      const handleOpenInfoWindow = useCallback((cluster) => {
        infoWindow.setContent(`Current Cluster Length: ${cluster.markers.length}`);
        infoWindow.setPosition(cluster.getCenter());
        infoWindow.open(cluster.map);
      
      const handleCloseInfoWindow = useCallback((cluster) => {
        infoWindow.close(cluster.map);
      }, []);
    
      return (
        <GoogleMap setMap={setMap}>
           <MarkerCluster onMouseOver={(cluster) => handleOpenInfoWindow(cluster)} onMouseOut={(cluster) => handleCloseInfoWindow(cluster)}
           // Your markers array map here to show markers
           </MarkerCluster>
        </GoogleMap>
      );
    }
    
    export default GoogleMapContainer