How to make a callback to Google Maps init in separate files of a web app

Since the Google Maps SDK script load a synchronic (due the async attribute), there is the callback parameter in the URL.

To solve the problem, you need to understand the async mechanism in google sdk

The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter.

https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API

So the solution is to load the script synchronic:

In the script tag that loads the Maps JavaScript API, it is possible to omit the async attribute and the callback parameter. This will cause the loading of the API to block until the API is downloaded.

This will probably slow your page load. But it means you can write subsequent script tags assuming that the API is already loaded.

https://developers.google.com/maps/documentation/javascript/tutorial#sync

  1. You can remove the async attribute that way, the page will stop running until the script will complete downloaded and run on the page. So, when the browser will get to your code, all the SDK object will be available.
  2. Now, since there is not code that calls to the initMap function (remember: who called it, it was the sdk script which call it only in the async mode), you need to call it by yourself. So, just call it in the end of the controller.

I could fix it in my code by using the callback and declaring the initMaps function on window as you did:

window.initMap = function(){
  //...
}

However, the trick was to load my custom JS (which also includes the above declaration of initMaps) before loading Google Maps:

<script async src="myCustomJsInclduingInitMapsFunction.js"></script>
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

Hope this helps.