Helen
Helen

Reputation: 187

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

My code is here: https://github.com/AlonaVa/NewRestaurants

Function UpdateBounds doesn't work properly:

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

My question is how can I automatically update bbox with the change of the map position?

Thank you!

Upvotes: 0

Views: 298

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10686

You need to create a component that uses useMapEvents within it, then that needs to be a child of the MapContainer.

This is working here:

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

Note I also added the whenCreated prop to grab the bounds once the map is loaded as well.

Working codesandbox

Upvotes: 1

Related Questions