Building projects with Leaflet and SvelteKit

Leaflet.js is still my go-to library when I need to make a map. Using Leaflet with vanilla Javascript is pretty simple: add the Leaflet library and CSS file, add a few lines of code and you’re done. The Leaflet site has a fantastic starter tutorial on this.

More recently I’ve been building projects in SvelteKit, which needs a slightly different setup to work. Mostly you need to account for things like checking whether the code is running in the browser.

This is the bare-bones SvelteKit-Leaflet setup I use for most projects.

Install Leaflet

Starting with a working SvelteKit app, install Leaflet:

npm i leaflet

Next …

Create a map component

Create a component file in the src/lib directory, or wherever you put your components files. In this example, I created it here: src/lib/Map.svelte/

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

let mapContainer;
let map;

onMount(async () => {
   if(browser) {
      const leaflet = await import('leaflet');
      map = leaflet.map(mapContainer).setView([-26.1925013,28.0100383], 13);

// Add the tile layer
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);

// Add a marker to the map
leaflet.marker([-26.1925013,28.0100383]).addTo(map)

   }
});

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


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

<style>
   @import 'leaflet/dist/leaflet.css';
   div {
   height: 500px;
   }
</style>

This loads onMount, OnDestroy and browser from Svelte. Then, if the code is running in a browser, Leaflet is loaded into the mapContainer div.

In the code above I set the view to a point in Johannesburg, South Africa:

.setView([-26.1925013,28.0100383]

You can also change the tile layers by altering the tile layer setup. The Leaflet Providers page is a good place to start looking for base maps.

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

Add component to page

Import the map component into the page and display.

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

<main>
    <Map />
</main>

This post is largely based on this post by Stanislav Khromov. I changed a few things and added some additional details.