Svelte MapLibre GL

repository·main·Indexed 43 days ago

https://github.com/mierune/svelte-maplibre-gl

A declarative, reactive Svelte 5 wrapper for MapLibre GL JS. It provides a component-based model for building interactive web maps, featuring a MapContext for safe state management of layers and sources, and extensions for Deck.gl, PMTiles, TerraDraw, and contour rendering.

Tokens
3.9K
Snippets
20
Records
25
Agent score
56%

What's inside Svelte MapLibre GL

  1. Overview of Svelte MapLibre GL

    main

    Svelte MapLibre GL provides a declarative and reactive interface for MapLibre GL JS using Svelte 5.

    Key characteristics:

    • Declarative & Reactive: Powered by Svelte 5 for idiomatic state management.
    • Flexible API: Designed to be minimally opinionated, making it accessible for beginners while remaining powerful for advanced users.
    • Imperative Support: You can still use traditional imperative MapLibre GL JS methods alongside the Svelte components to preserve full control.
  2. Manage map state with MapContext

    main

    The MapContext class is the central authority for managing the MapLibre GL map instance and its associated state (layers, sources, terrain, etc.) within a Svelte component tree. It provides reactive state and methods to safely interact with the map, even before the style has fully loaded.

    Key capabilities include:

    • Safe Map Operations: Methods like addLayer, removeLayer, addSource, and removeSource automatically wait for the map style to be loaded before executing.
    • Style Preservation: When changing the map style via setStyle, the context attempts to preserve user-added sources and layers, as well as user-defined configurations for light, projection, sky, and terrain.
    • Reactive State: Tracks userLayers and userSources using SvelteSet to keep track of what has been dynamically added by Svelte components.
    // Note: MapContext is typically managed via prepareMapContext()
    // and accessed via getMapContext() within the Svelte component tree.
  3. Add and remove layers using MapContext

    main

    Use MapContext to manage layers. These methods are safe to call even if the map style is still loading; the operations will be queued and executed once the style is ready.

    • addLayer(addLayerObject, beforeId?): Adds a layer. addLayerObject follows the maplibregl.AddLayerObject specification. beforeId is an optional ID of an existing layer to place this new layer before.
    • removeLayer(id): Removes the layer with the specified id.
    const mapCtx = getMapContext();
    
    // Adding a layer
    mapCtx.addLayer({
      id: 'my-layer',
      type: 'circle',
      source: 'my-source',
      paint: { 'circle-radius': 10 }
    });
    
    // Removing a layer
    mapCtx.removeLayer('my-layer');
  4. Initialize and access MapContext

    main

    To use the map context in a Svelte application, you must first initialize it in a parent component (usually where the map is instantiated) and then retrieve it in child components.

    • prepareMapContext(): Creates a new MapContext and sets it into the Svelte context. This should be called in a top-level map component.
    • getMapContext(): Retrieves the existing MapContext from the Svelte context. Throws an error if no context is found.
    // In a parent component
    import { prepareMapContext } from 'svelte-maplibre-gl';
    prepareMapContext();
    
    // In a child component
    import { getMapContext } from 'svelte-maplibre-gl';
    const mapCtx = getMapContext();
  5. Add sources and layers to the map

    main

    To display data, you must first define a source using components like VectorTileSource, GeoJSONSource, or RasterTileSource, and then add a layer (such as FillLayer, LineLayer, or SymbolLayer) that references that source. Layers are typically placed as children of the Map component.

    <script>
      import { Map, GeoJSONSource, FillLayer } from 'svelte-maplibre-gl';
      import myData from './data.json';
    </script>
    
    <Map>
      <GeoJSONSource data={myData} id="my-data" />
      <FillLayer source="my-data" />
    </Map>
  6. Add and remove sources using MapContext

    main

    Use MapContext to manage data sources. Like layers, these operations are queued until the map style is loaded.

    • addSource(id, source): Adds a source with the given id and source specification (e.g., GeoJSONSourceSpecification, RasterSourceSpecification).
    • removeSource(id): Removes the source with the specified id.
    const mapCtx = getMapContext();
    
    // Adding a source
    mapCtx.addSource('my-source', {
      type: 'geojson',
      data: { type: 'FeatureCollection', features: [] }
    });
    
    // Removing a source
    mapCtx.removeSource('my-source');
  7. Use MapLayerEventProps for layer event handlers

    main

    The MapLayerEventProps type is a utility that maps standard MapLibre GL layer event types to Svelte-friendly on<Event> prop names. For every event type available in maplibregl.MapLayerEventType, this type provides an optional handler function prefixed with on.

    For example, if MapLibre provides a click event, you can use onclick as a prop in your Svelte component. The event object passed to the handler will be the standard MapLibre event type for that specific event.

    // Example of how the mapping works conceptually:
    // If maplibregl.MapLayerEventType has: click: MapLayerEventType['click']
    // MapLayerEventProps will have: onclick?: (ev: maplibregl.MapLayerEventType['click']) => void;
  8. Add markers and popups

    main

    Use the Marker component to place points on the map and the Popup component to show information when a marker or feature is interacted with. Markers are typically children of the Map component.

    <script>
      import { Map, Marker, Popup } from 'svelte-maplibre-gl';
    </script>
    
    <Map>
      <Marker lng={10} lat={10}>
        <Popup>
          <p>Hello World!</p>
        </Popup>
      </Marker>
    </Map>