简体   繁体   中英

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!

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

Here is my solution:

Make sure you install the compatible versions:

  • react-leaflet-markercluster v2.0.0 or 2.0.0-rc3
  • leaflet 1.7.1
  • react-leaflet any version 2 will work
  • import 'react-leaflet-markercluster/dist/styles.min.css'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM