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 leafletNext …
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/
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: '©
Add component to page
Import the map component into the page and display.
This post is largely based on this post by Stanislav Khromov. I changed a few things and added some additional details.