带有 react-leaflet 2.0 的标记聚类 (Leaflet.markercluster)

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

正在尝试 Leaflet.markercluster 使用 react-leaflet 2。

https://github.com/OpenGov/react-leaflet-cluster-layer 似乎与 2.x.

不兼容

感谢任何让我入门的示例代码!

您可以使用本机传单代码制作您的 React 包装器以实现标记簇层:

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;
};

然后像这样使用它:

 <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>

我在演示中包含了一个案例,您可以使用按钮更改集群组图层。

希望这能帮助您入门。

Demo

这是我的解决方案:

确保安装兼容版本:

  • react-leaflet-markercluster v2.0.0 或 2.0.0-rc3
  • 传单 1.7.1
  • react-leaflet 任何版本 2 都可以工作
  • 进口'react-leaflet-markercluster/dist/styles.min.css'