avest
avest

Reputation: 53

How to tell google maps API loading script to look for callback inside the React componet?

In my rails app i use react.js(react-rails gem) to build the client side of my application.
I want to use google maps API in order to implement some geolocation feature.

class HomePage extends React.Component {
    constructor(props) {
        super(props)
    }

   initGeoTools(){
     console.log('callback invoked');
   }

   render () {
       return(
            <div>
            //..
            <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initGeoTools"
async defer></script>
            </div>
        );
    }
}

initGeoToolsis not a function - that implies that API script doesnt see callback function in this scope.

I have read somewhere that it should see this function in window scope. So I have tried to hack it like this:

class HomePage extends React.Component {
    constructor(props) {
        super(props)
    }

  componentWillMount(){
    window.initGeoTools = function(){
      console.log('callback invoked');
    }
}

   render () {
       return(
            <div>
            //..
            <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initGeoTools"
async defer></script>
            </div>
        );
    }
}

Indeed, that works but doesnt make sense in this context since from the function defined on window i have no access to react component stuff.

In a callback function i want to set state api_ready: true to indicate that API has been successfully loaded.

So the questions is how can i tell API script to look for callback function inside the React component?

Upvotes: 3

Views: 1665

Answers (1)

Diego Cardoso
Diego Cardoso

Reputation: 983

A week ago I have to do a Map component and I found this article where they used three scripts:

  • one to cache external scripts;
  • one to make the call for the Google Maps Api using the first one;
  • and the last one which is a Wrapper Component that you could use to connect with the maps api that's passed as props to the wrapped component.

Upvotes: 0

Related Questions