MapTiler SDK JS

repository·main·Indexed 41 days ago

https://github.com/maptiler/maptiler-sdk-js

A JavaScript and TypeScript map SDK tailored for MapTiler Cloud and built as an extension of MapLibre GL JS. Version 4.1.0 provides built-in support for vector tiles, satellite imagery, 3D terrain, and MapTiler API services like geocoding and search. It features support for both Web Mercator and Globe projections, customizable map styles via MapStyle shorthands, and a flexible system for programmatic and declarative UI controls.

Tokens
30.9K
Snippets
104
Records
136
Agent score
99%

What's inside MapTiler SDK JS

  1. Use Visitor language modes for labels

    main

    The SDK provides special built-in language modes to display labels in two languages simultaneously, which is helpful for users identifying places in non-Latin charsets.

    • Language.VISITOR: Concatenates labels in the user's system language and the local language.
    • Language.VISITOR_ENGLISH: Concatenates labels in English and the local language.
    const map = new Map({
      // some options...
      language: Language.VISITOR,
    });
    
    // or
    
    const map = new Map({
      // some options...
      language: Language.VISITOR_ENGLISH,
    });
  2. Center the map on the visitor's location

    main

    You can automatically center the map on a visitor using the MapTiler Geolocation API by passing the geolocate option to the Map constructor. This uses IP geolocation (precision of a few hundred meters) unless the user has previously granted browser location access.

    Strategies:

    1. maptilersdk.GeolocationType.POINT: Centers on the actual visitor location. If no zoom is provided, it defaults to 13.
    2. maptilersdk.GeolocationType.COUNTRY: Fits the map view to the bounding box of the visitor's country. The zoom option is ignored in this mode.

    Precedence Rules:

    • The center option takes precedence over geolocate.
    • If the hash option is true AND a location hash is already in the URL, geolocate is ignored.
    • If neither center nor hash is provided, the map defaults to the POINT strategy unless geolocate is set to false.
    // Center on visitor location
    new maptilersdk.Map({
      // ... other options
      geolocate: maptilersdk.GeolocationType.POINT,
    });
    
    // Fit visitor's country bounds
    new maptilersdk.Map({
      // ... other options
      geolocate: maptilersdk.GeolocationType.COUNTRY,
    });
  3. Configure Globe or Mercator projection

    main

    MapTiler SDK supports both the standard Web Mercator projection and the Globe projection. Mercator is the default. You can set the projection in three ways:

    1. In the Style JSON: Use the projection property.
    2. In the Map Constructor: Use the projection option. This overrides the style's projection and persists through style changes.
    3. Using map.setProjection(): Change the projection dynamically. Use the { persist: true } option to ensure the choice remains even if the map style is changed later.

    Note: The deprecated methods enableGlobeProjection() and enableMercatorProjection() also persist the projection.

    // In the constructor (persists through style changes)
    const map = new maptilersdk.Map({
      container: "map",
      projection: "globe",
    });
    
    // Dynamically changing and persisting
    map.setProjection("globe", { persist: true });
    
    // Dynamically changing without persistence (resets on next style change)
    map.setProjection("mercator");
    
    // Using MapLibre GL JS compatible object syntax
    map.setProjection({ type: "globe" });
  4. Use Static Maps via image URLs

    main

    MapTiler provides static maps as PNG, JPEG, or WebP images.

    Important: The static map functions do not perform network queries to the MapTiler API; instead, they return an image URL string. You should use these URLs directly in client-side <img> elements. Do not store or redistribute the static map files.

    There are three modes of operation:

    1. centered: Centered on a specific longitude/latitude and zoom level.
    2. bounded: Defined by a bounding box (south-west and north-east points).
    3. automatic: Automatically fits the map to include provided paths or markers.
  5. Handle Map lifecycle events

    main

    The SDK provides several lifecycle events to ensure the map and its components are ready before you interact with them:

    • ready: Fired after the load event, but specifically waits until all controls managed by the Map constructor are positioned. Use this instead of load if you plan to add custom controls via .addControl().
    • loadWithTerrain: Triggered only once when both the ready event and the terrain event (with non-null terrain) have fired. Use this when terrain: true is enabled to ensure animations like .flyTo() or .easeTo() work correctly without failing due to uninitialized terrain.
    • webglContextLost: Fired when the WebGL context is lost (e.g., due to GPU resource exhaustion). You can use this to trigger a page reload or re-instantiate the map.
    // Example: Using 'ready' to add a control
    const map = new maptilersdk.Map({
      container: "map-container",
    });
    
    map.on("ready", (evt) => {
      const terrainControl = new maptilersdk.MaptilerTerrainControl();
      map.addControl(terrainControl);
    });
    
    // Example: Handling WebGL context loss
    map.on("webglContextLost", (e) => {
      location.reload();
    });
  6. How ColorRamp resampling affects color distribution

    main

    Resampling changes how input values (typically in the range (0, 1)) map to colors.

    ease-out-sqrt

    Using .resample("ease-out-sqrt") compresses the lower (darker) part of the ramp and stretches the upper (lighter) part. This is useful for emphasizing changes in values at the lower end of a range (e.g., the (0, 0.4) range) because the color response changes more rapidly there.

    Example behavior with ColorRampCollection.GRAY:

    • Input 0 $\rightarrow$ (R:0, G:0, B:0)
    • Input 0.5 $\rightarrow$ (R:180, G:180, B:180)
    • Input 1 $\rightarrow$ (R:255, G:255, B:255)

    ease-in-square

    Using .resample("ease-in-square") makes the color change slower towards the lower end and faster towards the upper end of the range.

    Example behavior with ColorRampCollection.GRAY:

    • Input 0 $\rightarrow$ (R:0, G:0, B:0)
    • Input 0.5 $\rightarrow$ (R:64, G:64, G:64)
    • Input 1 $\rightarrow$ (R:255, G:255, B:255)
  7. Use Vector Layer Helpers

    main

    The helpers object provides simplified methods to create complex vector layers (points, polylines, polygons, heatmaps) in a single call. These helpers automatically create both the data source and the necessary layers with sensible defaults.

    Accessing Helpers:

    • ES Modules: import { helpers } from "@maptiler/sdk";
    • UMD/CDN: maptilersdk.helpers;

    Common Options for all Helpers:

    • data: A GeoJSON FeatureCollection, a URL to a GeoJSON/GPX/KML file, or a MapTiler dataset UUID.
    • layerId: Custom ID for the layer (auto-generated if omitted).
    • sourceId: Custom ID for the source (auto-generated if omitted).
    • beforeId: ID of an existing layer to insert this new layer underneath.
    • minzoom / maxzoom: Zoom visibility range.
  8. Basic Usage with ES modules

    main

    For advanced applications, use ES modules. You can configure your API key globally via the config object or pass it directly into the Map constructor. By default, the map initializes with the streets-v2 style.

    If you are using a framework like Next.js, you must manually import the SDK CSS (e.g., import "@maptiler/sdk/dist/maptiler-sdk.css";).

    import { config, Map } from "@maptiler/sdk";
    
    // Set API key globally
    config.apiKey = "YOUR_API_KEY";
    
    const mapContainer = document.getElementById("my-container-div");
    
    const map = new Map({
      container: mapContainer,
    });
  9. Wait for Map initialization using Promises

    main

    While you can use classic event callbacks (.on('load', ...)), the SDK provides modern async methods that return Promises. This allows for a linear, non-nested execution flow in async functions. These methods are available for events that occur only once in the lifecycle:

    • onLoadAsync(): Resolves when the load event fires.
    • onReadyAsync(): Resolves when the ready event fires.
    • onLoadWithTerrainAsync(): Resolves when the loadWithTerrain event fires.
    async function init() {
      const map = new Map({
        container,
        center: [2.34804, 48.85439],
        zoom: 14,
        terrain: true,
      });
    
      // Wait for the promise to resolve instead of using a callback
      await map.onLoadWithTerrainAsync();
    
      // Now safe to add sources, layers, or run animations
      map.addSource("my-source", { type: "geojson", data: ... });
      map.flyTo({ center: [-0.09956, 51.50509], zoom: 12.5 });
    }
  10. Basic Usage with CDN (UMD)

    main

    When using the CDN version, the SDK is available under the maptilersdk global object. You can set the API key via maptilersdk.config.apiKey and instantiate the map using new maptilersdk.Map(...).

    <script>
      // Add your MapTiler API key to the config
      maptilersdk.config.apiKey = "YOUR_API_KEY";
    
      const mapContainer = document.getElementById("my-container-div");
    
      const map = new maptilersdk.Map({
        container: mapContainer,
        style: maptilersdk.MapStyle.STREETS_DARK,
        hash: true,
      });
    </script>
  11. Add declarative custom controls via HTML

    main

    You can add controls using HTML attributes without writing JavaScript.

    1. Enable Detection: Set customControls: true or provide a CSS selector in the Map constructor:

    const map = new maptilersdk.Map({
      container: "map",
      customControls: true,
    });

    2. Declare Controls: Use the data-maptiler-control attribute on elements:

    • zoom-in: Zooms in
    • zoom-out: Zooms out
    • toggle-projection: Switches Mercator $\leftrightarrow$ Globe
    • toggle-terrain: Toggles terrain layer
    • reset-view: Resets bearing, pitch, and roll
    • reset-bearing: Resets bearing only
    • reset-pitch: Resets pitch only
    • reset-roll: Resets roll only
    • "" (empty): Registers the control without built-in functionality

    3. Grouping and Positioning:

    • Grouping: Wrap elements in a container with data-maptiler-control-group to style and position them together.
    • Positioning: Use data-maptiler-position on the element or the group. Valid values: 'top-left', 'top-right', 'bottom-left', 'bottom-right'.
    <!-- Grouped and positioned controls -->
    <div data-maptiler-control-group data-maptiler-position="bottom-right">
      <button data-maptiler-control="zoom-in">+</button>
      <button data-maptiler-control="zoom-out">−</button>
    </div>