0

I am using google-map-react and need to have access to the map.

I access the ref through doing something like:

<GoogleMap ref={ref => this.map = ref} />

When I call the ref on componentDidMount() like so this.map.map_ it returns null because the map has not loaded yet. I need a way to access this when the component mounts.

Taylor Austin
  • 5,407
  • 15
  • 58
  • 103

1 Answers1

1

I think you can use onGoogleApiLoaded:

handleGoogleApiLoaded = ({map, maps}) => {
  map...
}

<GoogleMap  
  onGoogleApiLoaded={this.handleGoogleApiLoaded}
  yesIWantToUseGoogleMapApiInternals
/>
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
  • If I set this to something like `this.map = map` in `componentDidMount()` it returns `undefined`. I may be able to make something work with this though – Taylor Austin Apr 30 '18 at 19:39
  • @TaylorAustin the thing is, you don't need `componentDidMount` there is a hook that will get called once the google map has loaded. See the edit. – Tomasz Mularczyk Apr 30 '18 at 19:41
  • Yeah that is what I ended up doing after I thought about it. Thank you, I know this is a "dangerous" way of doing this according to the warning. What could go wrong? And is there any other way of doing this with using `ref={ref => ref}` – Taylor Austin Apr 30 '18 at 19:47
  • 1
    Using ref to access internal component property is a "hacky" way, that's why there is no straight-forward way to do it. You would need to wait until GoogleMap and API are loaded and then use the ref. But you can't easily determine when this will happen. – Tomasz Mularczyk Apr 30 '18 at 19:52