Fix Google Maps API callback for async loading

The loading=async parameter requires a callback to notify when the API
is ready. Without a callback, google.maps is not properly initialized.

Use a global callback function with a timestamp suffix to handle the
async initialization properly, ensuring google.maps.Map constructor
is available when the component tries to initialize the map.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Eric Gullickson
2025-11-04 19:36:03 -06:00
parent 4151f58fa5
commit 8e52f3fb0e

View File

@@ -35,13 +35,9 @@ export function loadGoogleMaps(): Promise<void> {
return; return;
} }
// Create script tag // Create a global callback for Google Maps to call when ready
const script = document.createElement('script'); const callbackName = `gmapsCallback_${Date.now()}`;
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&loading=async&libraries=places`; (window as any)[callbackName] = () => {
script.async = true;
script.defer = true;
script.onload = () => {
if ((window as any).google?.maps) { if ((window as any).google?.maps) {
resolve(); resolve();
} else { } else {
@@ -49,11 +45,20 @@ export function loadGoogleMaps(): Promise<void> {
new Error('Google Maps loaded but window.google.maps not available') new Error('Google Maps loaded but window.google.maps not available')
); );
} }
// Clean up callback
delete (window as any)[callbackName];
}; };
// Create script tag with callback
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&loading=async&callback=${callbackName}&libraries=places`;
script.async = true;
script.defer = true;
script.onerror = () => { script.onerror = () => {
// Reset promise so retry is possible // Reset promise so retry is possible
mapsPromise = null; mapsPromise = null;
delete (window as any)[callbackName];
reject(new Error('Failed to load Google Maps script')); reject(new Error('Failed to load Google Maps script'));
}; };