This is the top result when you Google 'initMap function is not a function' so although there are a lot of answers already, I will make it very clear for the rookies like me what is happening.
To load a Google Map your page need 3 things:
- A
<div id="map"></div>
- Load the Google Map javascript.
- A function to initiate the map.
The div (easy)
The div is easy. The Google Map Javascript is easy but there is a catch.
Load Google Maps Javascript
<script
src="https://maps.googleapis.com/maps/api/jskey=YOURKEY&callback=initMap"
defer
></script>
There are two important parts of this script. defer, and the callback=initMap
First let's talk about defer. The defer
attribute causes the callback to execute after the full HTML document has been parsed. This makes sure your div is loaded and ready to be used by the javascript. However, does not mean that the Google Maps Javascript will load after your Javascript, and that is why the error happens sometimes.
The init function
You need to call a function to run the code that sets up the Google Map. The callback makes it easy because once the Google Maps code loads, it will call a function you tell it to load the map.
I'll repeat that because it is important. The callback=initMap is calling the initMap function in your code.
So if your code hasn't loaded by the time the Google Maps javascript loads, it will call initMap
but you get the error because it doesn't know what initMap is because your code, where you define initMap hasn't loaded yet.
This can happen seemingly randomly as network times vary. Sometimes you code loads first, and it works. Sometimes your code doesn't load first and Google Maps code loads first and you get the error.
Solution
There are a lot of solutions, but the one that I like is don't set a callback, and init the Map yourself after you know everything is loaded.
This way, we can load Google Maps Javascript async, which is faster since it loads in a separate process and doesn't wait for anything.
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY">
</script>
Notice how there is no callback set. So Google Map Javascript will not automatically call my init function, I have to call it when I know everything is ready.
We can do that with a window load event listener.
window.addEventListener("load", docReady);
function docReady() {
initMap();
}
The window load event fires after everything including Javascript has loaded.
Of course this might slow the page down as it has to load everything, including images, and then it will fire and initialize the map, but it ensures it will work every time.
As you learn more, you will learn other ways to make sure things load in the correct order. Good luck!