如何随着地图位置的变化更新地图的边界?

How to update the bounds of the map with the change of the map position?

我的代码在这里:https://github.com/AlonaVa/NewRestaurants

函数 UpdateBounds 无法正常工作:

const [bbox, setBbox] = useState(null);
function UpdateBounds () {
    const map = useMapEvent (()=>{
    setBbox (map.getBounds());
  }, [])
}

我的问题是如何根据地图位置的变化自动更新bbox?

谢谢!

您需要创建一个在其中使用 useMapEvents 的组件,然后它需要成为 MapContainer.

的子组件

这是在这里工作:

const MapEvents = ({ setBbox }) => {
  const setBounds = () => setBbox(map.getBounds());
  const map = useMapEvents({
    moveend: setBounds
  });
  return null;
};

const Map = (props) => {
  const [bbox, setBbox] = useState();

  return (
    <MapContainer
      zoom={zoom}
      center={center}
      whenCreated={(map) => setBbox(map.getBounds())}
    >

      <MapEvents setBbox={setBbox} />

      <TileLayerbburl="url" />
    </MapContainer>
  );
};

请注意,我还添加了 whenCreated 道具,以便在加载地图后抓取边界。

Working codesandbox