Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda