๐ก Home ๐ Chapter ๐ Prev ๐ Next
โกย GMapsBook.com is crafted by Jozef Sorocin (๐ขย Book a consulting hour) and powered by:
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.โ
You are likely:
new google.maps.Map(...)
or new google.maps.Marker(...)
const center = new google.maps.LatLng({...})
before google.maps
is fully initialized.
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>