动态放大以适合所有标记React-leaflet [英] zoom in dynamically to fit all the marker React-leaflet

查看:55
本文介绍了动态放大以适合所有标记React-leaflet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react-leaflet.在我的应用程序中显示地图.我也在地图上显示标记.问题是缩放级别不合适,因为有时标记可能彼此非常接近,有时它们会相距很远.是否有任何方法可以根据标记的距离设置缩放级别,以便用户可以一次查看所有标记?

I'm using react-leaflet. to show the map in my react app. I'm also showing marker on the map too. The problem is the zoom level is not appropriate because sometimes the marker might be quite near to each other and sometimes they will be very far apart. Is there any way to set the zoom level depending on the distance of the markers so that the user can see all the markers at once?

这是我的代码


<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

P.S: My react-leaflet version is 2.4.0

推荐答案

假设 MarkerClusterGroup

Assuming MarkerClusterGroup is a component from react-leaflet-markercluster package, the following example demonstartes how to auto-zoom to cover visible markers:

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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      <CustomLayer markers={markers} />
    </Map>
  );
}

这篇关于动态放大以适合所有标记React-leaflet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆