-2

I want to fetch Data and display in on react-google-maps

https://tomchentw.github.io/react-google-maps/#googlemap

The thing is that in order to fetch data, I need the maps bound as a query and I only get map bounds on onIdle

onIdle = () => {
    console.log('MAP IS READY');
    console.log('GET BOUNDS IN ON IDLE: ', this.mapRef.getBounds());
  }

If I fetch data on onIdle, the component will update the map and call onIdle again. It causes an infinitive loop.

My question is that what is the best place in react goole maps to fetch data (note that I need maps bounds). Or I just fetch it on onIdle and check if it is fetched before fetching

coinhndp
  • 2,281
  • 9
  • 33
  • 64
  • Please share codesandbox it would be easy to debug – Sakhi Mansoor Sep 06 '18 at 15:56
  • I want to fetch data only when I can get boundary of the map –  coinhndp Sep 06 '18 at 18:48
  • You need to pull the state for the markers (or whatever info you're fetching) out of the container for the map. In a few places in the container component, you will just need to leave the `map` element out of your dependency array. As long as markers, or whatever you're rendering, have key props, this should keep the infinite loop from starting. It's ugly, but it works. – Alexander Riccio Aug 06 '21 at 17:05

1 Answers1

0

Add listner for google maps, I'm not sure tilesloaded is the best event. You can try other events if it isn't.

const map = new google.maps.Map(...)
map.addListener('tilesloaded', () => {
    fetchYourDataHere().then((response) => {
         this.setState({googleMapsData: response})
    });
})

Also react refs may be helpful to get map instance.

Arseniy-II
  • 8,323
  • 5
  • 24
  • 49