๐Ÿ“–

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.