All integrations MapLibre Leaflet OpenLayers React Vue Svelte Angular React Native WordPress Webflow Squarespace Wix Shopify API docs

ExpressMaps in Svelte

A Svelte 5 component around MapLibre GL JS, using runes, that works in plain Svelte and in SvelteKit with server-side rendering. The map below is the same MapLibre setup in the Subtle style.

1. Install MapLibre GL JS

The examples are for Svelte 5 and MapLibre GL JS 6, the current major versions, built with Vite (which SvelteKit uses).

npm install maplibre-gl

Put your key in .env. SvelteKit only exposes variables with the PUBLIC_ prefix to the browser. Create a key in the console.

PUBLIC_EXPRESSMAPS_KEY=YOUR_API_KEY

2. The map component

Create the map in onMount. It only runs in the browser, after the container element exists, so the component is safe to server-render; the function it returns removes the map when the component is destroyed.

<!-- src/lib/ExpressMap.svelte -->
<script>
  import { onMount } from "svelte";
  import { Map, Marker, NavigationControl, Popup, setWorkerUrl } from "maplibre-gl";
  import "maplibre-gl/dist/maplibre-gl.css";
  import workerUrl from "maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url";
  import { PUBLIC_EXPRESSMAPS_KEY as KEY } from "$env/static/public";

  let { mapStyle = "standard", center = [-0.1276, 51.5072], zoom = 12, popup = "" } = $props();

  const styleUrl = (id) => `https://tiles.expressmaps.com/styles/${id}.json?key=${KEY}`;

  let container;
  let map = $state.raw(null);
  let shown = mapStyle;

  onMount(() => {
    setWorkerUrl(workerUrl);
    map = new Map({ container, style: styleUrl(mapStyle), center, zoom });
    map.addControl(new NavigationControl(), "top-right");

    const marker = new Marker().setLngLat(center).addTo(map);
    if (popup) marker.setPopup(new Popup().setText(popup));

    return () => map.remove();
  });

  // Follow changes to the mapStyle prop
  $effect(() => {
    if (map && mapStyle !== shown) {
      map.setStyle(styleUrl(mapStyle));
      shown = mapStyle;
    }
  });
</script>

<div bind:this={container} class="map"></div>

<style>
  .map { width: 100%; height: 400px; }
</style>

Use it in any page:

<script>
  import ExpressMap from "$lib/ExpressMap.svelte";
</script>

<ExpressMap center={[-0.1276, 51.5072]} zoom={12} popup="Our office" />

$state.raw keeps the map instance out of Svelte's deep reactivity, which would otherwise wrap it in a proxy. The worker import is MapLibre's documented Vite setup for version 6: without setWorkerUrl no tiles are drawn. On MapLibre 5 or earlier, leave out the worker lines. Outside SvelteKit, replace the $env import with import.meta.env.VITE_EXPRESSMAPS_KEY.

Markers, popups and your own data

Inside onMount you are writing ordinary MapLibre code. Add GeoJSON layers once the map has loaded. MapLibre uses [lng, lat] order.

map.on("load", () => {
  map.addSource("stores", { type: "geojson", data: "/stores.geojson" });
  map.addLayer({
    id: "stores",
    type: "circle",
    source: "stores",
    paint: { "circle-radius": 6, "circle-color": "#1a73e8", "circle-stroke-width": 2, "circle-stroke-color": "#fff" }
  });
  map.on("click", "stores", (e) => {
    new Popup().setLngLat(e.lngLat).setText(e.features[0].properties.name).addTo(map);
  });
});

Switching style

The component follows its mapStyle prop, so <ExpressMap mapStyle={dark ? "darklands" : "standard"} /> tracks your app's theme. Any of the ten styles work: standard, basic, enhanced, darklands, greyscale, navigator, subtle, autobahn, lithium and mulberry.

map.setStyle() replaces the whole style, including layers you added yourself. For a style picker that keeps your sources and layers, use the StyleSwitcher control from the optional expressmaps package. Its createMap() helper also replaces most of the setup:

npm install expressmaps maplibre-gl
import * as maplibregl from "maplibre-gl";
import { createMap, StyleSwitcher } from "expressmaps";
import "expressmaps/expressmaps.css";

onMount(() => {
  maplibregl.setWorkerUrl(workerUrl);
  const map = createMap({
    maplibregl,
    container,
    key: KEY,
    style: "standard",
    center: [-0.1276, 51.5072],
    zoom: 12,
    marker: { popup: "Our office" }
  });
  map.addControl(new StyleSwitcher({ key: KEY, styles: ["standard", "subtle", "darklands"] }), "top-left");
  return () => map.remove();
});

SvelteKit and server-side rendering

SvelteKit renders pages on the server first. MapLibre needs a browser and WebGL, and onMount does not run on the server, so creating the map there is all that is required. Do not create it in the component's top-level script, in a load function or in $effect.pre.

If your server build still fails while importing maplibre-gl, load it inside onMount instead, so it is never imported on the server:

onMount(() => {
  let map;
  import("maplibre-gl").then(({ Map, setWorkerUrl }) => {
    setWorkerUrl(workerUrl);
    map = new Map({ container, style: styleUrl(mapStyle), center, zoom });
  });
  return () => map?.remove();
});

For a page that is only a map, you can also turn off server rendering for that route with export const ssr = false; in its +page.js.

Things to know

  • The key ends up in your client bundle, which is normal for web maps. Restrict it to your domains in the console; requests from other sites are refused.
  • One map load is counted each time the map is created. Switching style on an existing map does not count as another load, and panning and zooming are free. Destroying and recreating the component (for example inside {#if} or on navigation) counts again.
  • The free plan includes 100,000 map loads a month.
  • Keep the attribution control on. The OpenStreetMap credit comes from the style and is required by the data licence.
  • Component libraries such as svelte-maplibre-gl offer declarative markers, layers and controls; they take the same style URL.

New to MapLibre? The MapLibre GL JS guide covers the map API in more detail. Sign up for a free API key to get started.

Get a free API key MapLibre guide