Incorporating the Google Maps API into my svelte project has been a task. I've turned to the js-api-loader npm package for this purpose.
Below is the code snippet I'm using to load the Google API:
loader.js
import { Loader } from '@googlemaps/js-api-loader';
let googleIsLoaded = false;
async function loadGoogleMapsAPI() {
if (!googleIsLoaded) {
const libraries = ['places'];
try {
const loader = new Loader({
apiKey: API_KEY,
version: 'weekly',
libraries,
});
console.info('Loading Google API ...'); // LOGGED 1st -> OK
await loader.load();
console.info('Google API is loaded'); // LOGGED 6th -> KO
googleIsLoaded = true;
} catch (error) {
throw new Error(`Google API Loader failed ${error.message}`);
}
}
}
Upon loading the page, it first accesses the route specified in route/index.svelte:
<script context="module">
export const ssr = false;
</script>
<script>
import MyComp from '$components/MyComp.svelte';
import { loadGoogleMapsAPI } from '$lib/loader.js';
init();
async function init() {
try {
await loadGoogleMapsAPI();
} catch (e) {
console.error(e);
}
}
<MyComp />
Subsequently, MyComp.svelte is loaded:
import { onMount } from 'svelte';
let google;
onMount(() => {
console.log('mounted'); // LOGGED 2nd -> OK
google = window.google;
if (google === undefined) {
console.log('google is undefined'); // LOGGED 3rd -> OK
sleep(5000, init());
} else {
console.log('google is defined');
}
});
async function init() {
...
autocompleteWidget = new google.maps.places.Autocomplete(input, options);
/////////// LOGGED 5th -> KO: EXCEPTION GOOGLE IS NOT DEFINED /////////
}
and here's the helper function used for sleeping:
helpers.js
export async function sleep(time, fn, ...args) {
console.info('sleep ' + time + 'ms'); // LOGGED 4th -> OK
await timeout(time);
console.info('woken'); // LOGGED 7th -> KO
return fn(...args);
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
However, there seems to be an issue as the `init()` function is invoked disregarding the `sleep(5000, init())` call :/
Thank you for your assistance.
console
loader.js: Loading Google API ...
MyComp.svelte: mounted
MyComp.svelte: google is undefined
helpers.js: sleep 5000ms
MyComp.svelte:106 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'maps')
helpers.js: Google API is loaded
helpers.js: woken