๐Ÿก Home ๐Ÿ“– Chapter ๐Ÿ‘ˆ Prev ๐Ÿ‘‰ Next

โšกย  GMapsBook.com is crafted by Jozef Sorocin (๐ŸŸขย Book a consulting hour) and powered by:

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"></script>

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:

before google.maps is fully initialized.

https://tally.so/r/w2a2jM

Solutions

A) Use dynamic loading

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

import { Loader } from "@googlemaps/js-api-loader"

const loader = new Loader({
  apiKey: "Aiza",
  version: "weekly",
  // ... additional options
});

loader.load().then(async () => {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: 42, lng: 42 },
    zoom: 16,
  });
});

<aside> ๐Ÿ’ก Notice how you donโ€™t call google.maps.Map directly but rather asynchronously import the Map library and go from there. As such, the โ€œCannot read property 'maps' of undefinedโ€ error cannot possibly happen.

</aside>