initMap is not a function

前端 未结 4 366
南旧
南旧 2021-01-23 01:35

I can\'t understand what is the problem? I used this example from Google Map APIs: Simple Map


   
   
4条回答
  •  一整个雨季
    2021-01-23 02:34

    None of the solutions offered were helping me. I finally came across dynamic loading of the script here: https://developers.google.com/maps/documentation/javascript/overview#Loading_the_Maps_API

    Because you are loading it in a separate js file the google map api's are not loading in the correct order with the function.

    Doing this solved it for me:

    // Create the script tag, set the appropriate attributes
    var script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
    script.defer = true;
        
    // Attach your callback function to the `window` object
    window.initMap = function() {
          // JS API is loaded and available
          // Throw your code within this, it will wait for the google api scripts to completely load
    };
        
    // Append the 'script' element to 'head'
    document.head.appendChild(script);
    

    Hope this helps, I spent a day looking for solution.

提交回复
热议问题