Search code examples
javascriptreactjsleafletreact-leafletleaflet.markercluster

Marker Clustering (Leaflet.markercluster) with react-leaflet 2.0


Trying to get Leaflet.markercluster working with react-leaflet 2.

https://github.com/OpenGov/react-leaflet-cluster-layer does not appear to be compatible with 2.x.

Any example code to get me started is appreciated!


Solution

  • You can make your React wrapper using native leaflet code to achieve a marker cluster layer:

    const mcg = L.markerClusterGroup();
    
    const MarkerCluster = ({ markers }) => {
      const { map } = useLeaflet();
    
      useEffect(() => {
        mcg.clearLayers();
        markers.forEach(({ position, text }) =>
          L.marker(new L.LatLng(position.lat, position.lng), {
            icon: customMarker
          })
            .addTo(mcg)
            .bindPopup(text)
        );
    
        // optionally center the map around the markers
        // map.fitBounds(mcg.getBounds());
        // // add the marker cluster group to the map
        map.addLayer(mcg);
      }, [markers, map]);
    
      return null;
    };
    

    and then use it like this:

     <Map center={position} zoom={2} style={mapStyle} maxZoom={20}>
            <TileLayer
              url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
            <MarkerCluster markers={markers} />
    </Map>
    

    I included a case in the demo where you can change the cluster group layer using a button.

    Hopefully this will get you started.

    Demo