我正在使用 react 传单。在我的 react 应用程序中显示 map 。我也在 map 上显示了标记。问题是缩放级别不合适,因为有时标记可能彼此非常接近,有时它们会相距很远。有没有办法根据标记的距离设置缩放级别,以便用户可以一次看到所有标记?
这是我的代码
<Map center={center} maxZoom={9} zoom={5}>
<MarkerClusterGroup showCoverageOnHover={false}>
{
markers.map(({fillColor, position, id}) =>
<CircleMarker fillColor={fillColor} color={darken(0.1, fillColor)} radius={10} fillOpacity={1} key={id} center={position} onClick={this.onClick} />
}
</MarkerClusterGroup>
</Map>
P.S:我的react-leaflet版本是2.4.0
最佳答案
假设 MarkerClusterGroup
是 react-leaflet-markercluster
中的一个组件包中,以下示例演示了如何自动缩放以覆盖可见标记:
function CustomLayer(props) {
const groupRef = useRef(null);
const { markers } = props;
const mapContext = useLeaflet();
const { map} = mapContext; //get map instance
useEffect(() => {
const group = groupRef.current.leafletElement; //get leaflet.markercluster instance
map.fitBounds(group.getBounds()); //zoom to cover visible markers
}, []);
return (
<MarkerClusterGroup ref={groupRef} showCoverageOnHover={false}>
{markers.map(({ fillColor, position, id }) => (
<CircleMarker
fillColor={fillColor}
radius={10}
fillOpacity={1}
key={id}
center={position}
/>
))}
</MarkerClusterGroup>
);
}
使用
function MapExample(props) {
const { markers, center } = props;
return (
<Map center={center} maxZoom={9} zoom={5}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<CustomLayer markers={markers} />
</Map>
);
}
关于reactjs - 动态放大以适应所有标记 React-leaflet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61638254/