window.initMap is not a function

Have you ever encountered the ‘window.initMap is not a function’ error when trying to load Google Maps in your HTML?

If yes, then you are not alone. Many developers, including myself, have been through the same issue. I’ve searched through countless Stack Overflow posts and other resources online, only to find that the commonly suggested solutions (like adjusting scripts order or using ‘defer’ and ‘async’) don’t actually solve the problem.

Eventually, I decided to consult with Google Map’s colleague. Bard. They suggested the following solution:

window.initMap = function () {
// Your Google Maps initialization code here...
}
const googleMapsScript = document.createElement('script');
googleMapsScript.src = 'https://maps.googleapis.com/maps/api/js?key=xxxx&callback=initMap';
document.head.appendChild(googleMapsScript);

In the above script, we first define the window.initMap function. Then, we create a new script element and append it to the document’s head, loading Google Maps.

This approach effectively resolves the ‘window.initMap is not a function’ error.

I hope this post helps you solve this issue. Happy coding!

Silviu Stroe
I'm Silviu and I run Brainic, a mobile-focused software agency. I'm also a member of Nokia and Yahoo wall of fame. My interests are in low-code/no-code development and bleeding-edge technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *