Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Access Variables Created During onMount in Svelte

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!