I'm working my first Svelte app which includes an embedded Google Map.
Setup Google Maps With Svelte 3 provided a good starting point for creating a component which asynchronously loads a Google Map. However, I can't figure out how to access the map object outside the initial onMount call, and without access to that object I can't add in functionality I want (for example, re-centering the map based on a button the user clicks).
main.js
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
ready: false,
}
});
window.initMap = function ready() {
app.$set({ ready: true });
}
export default app;
App.svelte
<script>
import Map from './Map.svelte';
export let ready;
</script>
<svelte:head>
<script defer async src="https://maps.googleapis.com/maps/api/js?key={}&callback=initMap"></script>
</svelte:head>
{ #if ready }
<Map></Map>
{ /if }
Map.svelte
<script>
// Imports
import { onMount } from 'svelte';
// Globals
let map;
let container;
// Load the map async
onMount(async () => {
map = new google.maps.Map(container, {
zoom: 6,
center: { lat: 0, lng: 0 },
});
});
// This function has no access to the `map` variable created above!!
function recenterMap() {
map.setCenter({lat: 1, lng: 1});
}
</script>
<div class="full-screen" bind:this={container}></div>
<button on:click="{recenterMap}"></button>
Running the above gives an error for trying to invoke the setCenter call on an object that does not exist. I've searched for how other frameworks (React, Vue) might handle this, but the solutions are specific to the frameworks and are not applicable here.
Any help would be greatly appreciated!