13

When I had my Google Maps API snippet:

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

in index.html, I got the error:

Uncaught InvalidValueError: initMap is not a function

I want to keep all of my bower_component, CSS, API, and script declarations in my index.html file on my Yeoman-scaffolded AngularJS web app. The map I was actually trying to recreate would be on another route, let's call it route "afterlogin", just a basic map. I separated the js and the html html components into afterlogin.js and afterlogin.html

There are a number of potential causes for this. One of which was presented here as a matter of adjusting the call to match the namespace, https://stackoverflow.com/a/34466824/1923016 . Would this require an angular service? If so, how would the service work into the initMap function and its call in the Google maps api snippet?

One of the complications is the order. I'm new to web app dev, but from what I can tell the index.html loads first, uses the url in the snippet to make the callback to the initMap function which is not featured in <script>...</script> in the index.html file nor in the app.js file. Instead, since the init function is in a route's js code, it cannot be seen, hence the need for some kind of "namespace" version of the call. This leads to a console error even from the login route, which is not even where the div for the map is.

---- EDIT: ----

Also note that in this case, this did not do the trick:

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

This also does not apply, as the function is never called: Uncaught InvalidValueError: initMap is not a function

-- -- -- -- -- --

afterlogin.js

angular.module('myappproject').controller('AfterloginCtrl', function ($scope) {

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 17,
      center: {lat: -33.8666, lng: 151.1958}
    });

    var marker = new google.maps.Marker({
      map: map,
      // Define the place with a location, and a query string.
      place: {
        location: {lat: -33.8666, lng: 151.1958},
        query: 'Google, Sydney, Australia'

      },
      // Attributions help users find your site again.
      attribution: {
        source: 'Google Maps JavaScript API',
        webUrl: 'https://developers.google.com/maps/'
      }
    });

    // Construct a new InfoWindow.
    var infoWindow = new google.maps.InfoWindow({
      content: 'Google Sydney'
    });

    // Opens the InfoWindow when marker is clicked.
    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  }
 });

afterlogin.html

<!DOCTYPE html>
<html>
    <head>
        <title>after login page</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
                }
            #map {
                height: 100%;
            }
        </style>
    </head>
    <body>

        <div id="map"></div>
        
    </body>
</html>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
AlleyOOP
  • 1,536
  • 4
  • 20
  • 43

3 Answers3

20

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.
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • 1
    This is a solution. Yet I find this unsatisfactory, because loading Maps synchronously slows page loading a lot. Is there really no way to use the Google Maps callback in the async case? – morgler Nov 08 '18 at 13:59
  • You can add this script at the end of the `body` and it will not break the rendering (yet it will delay the `window.load` event). When you use `async` you have to make sure that the script is downloaded and executed before you can create the map. If you want, you can detect the script state by ([this](https://stackoverflow.com/questions/34076200/check-when-async-javascript-file-is-loaded)) – Mosh Feu Nov 08 '18 at 15:04
10

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.

morgler
  • 1,669
  • 1
  • 18
  • 26
  • 1
    I was hoping this would work but there`s a reciprocal error in that logic, that is, `Uncaught ReferenceError: google is not defined` from my initMap function which calls `var map = new google.maps.Map(...)`. So unless I can load the Google maps script in my custom script, this will not work as far as I can tell. – David Gaskin Apr 04 '19 at 08:17
  • Does not seem to work, maps code complains `initMap is not a function`. – crazypeter Nov 27 '19 at 18:17
  • 2
    Actually, it does work. But in Typescript I had to use `window['initMaps'] = function() { ... }`. Simply using `window.initMaps = ...` did not work. – crazypeter Nov 27 '19 at 18:30
0
window.initMap = function(){
  //...
}

works with defer script in the googlemaps api link without async, tested for shopify as well and this works great, just make sure to give a height to the map