How to update the bounds of the map with the change of the map position?
Asked Answered
T

1

0

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!

Technology answered 10/3, 2021 at 9:44 Comment(3)
Please post your code snippet that you are having trouble with, and explain in more detail what you are having an issue with. We shouldn't have to read an entire repo searching for your bug :)Leatherleaf
What do you mean by map position change? Map position can change when doing multiple actions. When you drag the map f.i with the mouse or when sth else occurs?Vernita
I think everything (scale change, move). For me it is important to have the list of restaurants, markers of which I can see at this moment on the mapTechnology
O
1

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

Otorhinolaryngology answered 10/3, 2021 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.