Stanislav Khromov

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

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

Create the file src/lib/LeafletMap.svelte

    import { onMount } from 'svelte';
    import { browser } from '$app/env';

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

            const map ='map').setView([51.505, -0.09], 13);

            leaflet.tileLayer('https://{s}{z}/{x}/{y}.png', {
                attribution: '© <a href="">OpenStreetMap</a> contributors'

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

    <div id="map"></div>

    @import '';
    main #map {
        height: 800px;

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

	import LeafletMap from '$lib/LeafletMap.svelte';

	<LeafletMap />

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

Web Developer at Aftonbladet (Schibsted Media Group)

View Comments

There are currently no comments.

Next Post