Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda