Chris
Chris

Reputation: 1475

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>

Upvotes: 0

Views: 210

Answers (1)

brunnerh
brunnerh

Reputation: 185072

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

$: if (map) map.flyTo(...)

Upvotes: 1

Related Questions