📖

Cannot Read Property 'maps' of Undefined

🏡 Home 📖 Chapter 👈 Prev 👉 Next
⚡  GMapsBook.com is crafted by Jozef Sorocin and powered by:
  • g-Xperts (Google Cloud & Business Profile Partner)
 

Error explanation

As we discussed in 🗺️ Creating a New Google Map, it’s customary to provide a callback URL parameter in the initialization script:
< script async defer src="https://.../api/js?key=Aiza...&callback=initMap">
Note that initMap must be a globally accessible function (i.e. window.initMap).
The callback parameter ensures that the application logic where you call google.maps.XYZ is only run when the global window.google is properly initialized.
If window.google isn’t initialized just yet, it’s undefined. Thus, calling window.google.maps.XYZ is interpreted as undefined.maps which errors out and prints the message “Cannot read property 'maps' of undefined.”

Likely causes

You are likely:
  • instantiating Google Maps classes like new google.maps.Map(...) or new google.maps.Marker(...)
  • or defining constants like const center = new google.maps.LatLng({...})
before google.maps is fully initialized.

Solutions

A) Use dynamic loading

To load Google Maps on-demand and without a <script> tag, install @googlemaps/js-api-loader and run:

Already purchased? Sign in here.