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

问题描述 投票:0回答:1

试图让Leaflet.markercluster与react-leaflet 2一起使用。

[https://github.com/OpenGov/react-leaflet-cluster-layer似乎与2.x不兼容。

感谢任何入门示例代码!

reactjs leaflet react-leaflet leaflet.markercluster
1个回答
1
投票

您可以使用本机传单代码来实现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

© www.soinside.com 2019 - 2024. All rights reserved.