Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FlyTo on existing Mapbox Object in Svelte

I have a Svelte application with a Map component as below. I’d like to pass in props for centreCoords and Zoom and then fly to them when they change outside the component.

However, I can’t work out how to get the map object outside the onMount function.

<script>
    import { onMount, onDestroy } from 'svelte';
    import mapboxgl from 'mapbox-gl';
    const token = 'xxx';

    let mapElement;
    let map;
    export let zoom;
    export let centreCoords = [];

    // This but doesn't work
    map.flyTo({
        center: centreCoords,
        zoom: zoom,
        essential: true // this animation is considered essential with respect to prefers-reduced-motion
    });

    onMount(() => {
        mapboxgl.accessToken = token;
        map = new mapboxgl.Map({
            container: mapElement,
            zoom: zoom,
            center: centreCoords,
            // Choose from Mapbox's core styles, or make your own style with Mapbox Studio
            style: 'mapbox://styles/mapbox/light-v10',
            antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
        });

    });

    onDestroy(async () => {
        if (map) {
            map.remove();
        }
    });
</script>



<main>
    <div bind:this={mapElement} />
</main>

<style>
    @import 'mapbox-gl/dist/mapbox-gl.css';
    main div {
        height: 800px;
    }
</style>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Should be possible to just use a reactive statement with an if:

$: if (map) map.flyTo(...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading