@@ -7,7 +7,7 @@ const GOOGLE_API_KEY = "AIzaSyCXRaA3liul4_0D5MXLybx9s3s_o_Q2opI";
77let scriptLoaded = false ;
88
99// Track already loaded libraries
10- const loadedLibraries = new Set ( ) ;
10+ const loadedLibraries = new Map ( ) ;
1111
1212async function init ( ) {
1313 await loadGoogleMaps ( ) ; // Load core script
@@ -42,18 +42,36 @@ function loadGoogleMaps() {
4242
4343// Load additional libraries dynamically using importLibrary
4444async function loadLibrary ( library ) {
45+ // Check if the library's promise is already stored in the Map
4546 if ( loadedLibraries . has ( library ) ) {
46- console . log ( `Library "${ library } " is already loaded.` ) ;
47- return ; // Skip if already loaded
47+ return loadedLibraries . get ( library ) ; // Return the existing promise
4848 }
4949
50- try {
51- await window . google . maps . importLibrary ( library ) ;
52- loadedLibraries . add ( library ) ;
53- console . log ( `Loaded library: ${ library } ` ) ;
54- } catch ( error ) {
55- console . error ( `Failed to load library "${ library } ":` , error ) ;
56- }
50+ // Attempt to load the library using the `importLibrary`
51+ const libraryPromise = window . google . maps
52+ . importLibrary ( library )
53+ . then ( ( ) => {
54+ console . log (
55+ `Google Maps library "${ library } " loaded successfully.`
56+ ) ;
57+ loadedLibraries . set ( library , libraryPromise ) ; // Confirm the library is loaded by storing the promise
58+ return window . google . maps [ library ] ; // Return the loaded library instance if you need it
59+ } )
60+ . catch ( ( error ) => {
61+ console . error (
62+ `Failed to load Google Maps library "${ library } ":` ,
63+ error
64+ ) ;
65+ loadedLibraries . delete ( library ) ; // Remove the library if loading failed
66+ throw error ; // Rethrow the error for further handling
67+ } ) ;
68+
69+ // Store the promise in the Map for caching
70+ loadedLibraries . set ( library , libraryPromise ) ;
71+
72+ // Await the resolution of the library before returning
73+ const resolvedLibrary = await libraryPromise ;
74+ return resolvedLibrary ;
5775}
5876
5977// Initialize Google Maps elements dynamically
0 commit comments