DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Using Leaflet with SvelteKit
Stanislav Khromov
Stanislav Khromov

Posted on • Updated on • Originally published at khromov.se

Using Leaflet with SvelteKit

Having just started on a new SvelteKit project, I was tasked with implementing a Leaflet component.

Using Leaflet in SvelteKit is a bit tricky due to its dependency on the window object and the way SvelteKit builds its production bundle, but it is fully possible, so let's do that in this post. We're going to assume that you have a working SvelteKit app. If not, follow the official guide first!

Let's start out by installing leaflet:

npm i leaflet
Enter fullscreen mode Exit fullscreen mode

Now we can create a simple Svelte component based on the Leaflet Quick Start guide!

Create the file src/lib/LeafletMap.svelte

<script>
    import { onMount, onDestroy } from 'svelte';
    import { browser } from '$app/env';

    let mapElement;
    let map;

    onMount(async () => {
        if(browser) {
            const leaflet = await import('leaflet');

            map = leaflet.map(mapElement).setView([51.505, -0.09], 13);

            leaflet.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            leaflet.marker([51.5, -0.09]).addTo(map)
                .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
                .openPopup();
        }
    });

    onDestroy(async () => {
        if(map) {
            console.log('Unloading Leaflet map.');
            map.remove();
        }
    });
</script>


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

<style>
    @import 'leaflet/dist/leaflet.css';
    main div {
        height: 800px;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Finally, add your new component to your src/routes/index.svelte file:

<script>
    import LeafletMap from '$lib/LeafletMap.svelte';
</script>

<main>
    <LeafletMap />
</main>
Enter fullscreen mode Exit fullscreen mode

Now it's time to start the dev server with npm run dev and visit http://localhost:3000/ to marvel at the results:

Resulting map

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.