How to display a style switcher control

This tutorial demonstrates the process of showcasing a control for switching styles on the map.

  1. Install the npm package.

    npm install --save @maptiler/sdk
    Bash
  2. Include the CSS file.

    If you have a bundler that can handle CSS, you can import the CSS or include it with a <link> in the head of the document via the CDN

    import "@maptiler/sdk/dist/maptiler-sdk.css";
    JavaScript
    HTML
  3. Include the following code in your JavaScript file (Example: app.js).

    import * as maptilersdk from '@maptiler/sdk';
    
    maptilersdk.config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
    const map = new maptilersdk.Map({
      container: 'map', // container's id or the HTML element to render the map
      style: maptilersdk.MapStyle.STREETS,
      center: [100.507, 13.7231], // starting position [lng, lat]
      zoom: 10.82, // starting zoom
    });
    JavaScript
  1. Replace YOUR_MAPTILER_API_KEY_HERE with your actual MapTiler API key.

  2. The next is up to you. You can center your map wherever you desire (modifying the starting position) and set an appropriate zoom level (modifying the starting zoom) to match your users’ needs. Additionally, you can change the map’s look (by updating the source URL); choose from a range of visually appealing map styles from our extensive MapTiler standard maps, or create your own to truly differentiate your application.

  1. Create the list of styles. In the list of styles use as key the ID of the map in MapTiler Cloud.

    const baseMaps = {
      "STREETS": {
        img: "https://cloud.maptiler.com/static/img/maps/streets.png"
      },
      "WINTER": {
        img: "https://cloud.maptiler.com/static/img/maps/winter.png"
      },
      "HYBRID": {
        img: "https://cloud.maptiler.com/static/img/maps/hybrid.png"
      }
    }
    JavaScript
  2. Select the initial style from the list and update the map style URL.

    const initialStyle = maptilersdk.MapStyle[Object.keys(baseMaps)[0]];
    const map = new maplibregl.Map({
      container: 'map', // container id
      style: initialStyle,
      center: [100.507, 13.7231], // starting position [lng, lat]
      zoom: 10.82 // starting zoom
    });
    JavaScript
  3. Create the styleSwitcherControl and add it to the map. This code is an adaptation of the maplibre-gl-basemaps plugins.

    class layerSwitcherControl {
    
      constructor(options) {
        this._options = {...options};
        this._container = document.createElement("div");
        this._container.classList.add("maplibregl-ctrl");
        this._container.classList.add("maplibregl-ctrl-basemaps");
        this._container.classList.add("closed");
        switch (this._options.expandDirection || "right") {
          case "top":
            this._container.classList.add("reverse");
          case "down":
            this._container.classList.add("column");
            break;
          case "left":
            this._container.classList.add("reverse");
          case "right":
            this._container.classList.add("row");
        }
        this._container.addEventListener("mouseenter", () => {
          this._container.classList.remove("closed");
        });
        this._container.addEventListener("mouseleave", () => {
          this._container.classList.add("closed");
        });
      }
    
      onAdd(map) {
        this._map = map;
        const basemaps = this._options.basemaps;
        Object.keys(basemaps).forEach((layerId) => {
          const base = basemaps[layerId];
          const basemapContainer = document.createElement("img");
          basemapContainer.src = base.img;
          basemapContainer.classList.add("basemap");
          basemapContainer.dataset.id = layerId;
          basemapContainer.addEventListener("click", () => {
            const activeElement = this._container.querySelector(".active");
            activeElement.classList.remove("active");
            basemapContainer.classList.add("active");
            map.setStyle(maptilersdk.MapStyle[layerId]);
          });
          basemapContainer.classList.add("hidden");
          this._container.appendChild(basemapContainer);
          if (this._options.initialBasemap.id === layerId) {
              basemapContainer.classList.add("active");
          }
        });
        return this._container;
      }
    
      onRemove(){
        this._container.parentNode?.removeChild(this._container);
        delete this._map;
      }
    }
    
    map.addControl(new layerSwitcherControl({basemaps: baseMaps, initialBasemap: initialStyle}), 'bottom-left');
    JavaScript
  4. Create the styleSwitcherControl css style. Add the SwitcherControl style to your stylesheet.

    /*layerSwitcherControl*/
    .maplibregl-ctrl-basemaps {
      display: flex;
      flex-direction: row;
      pointer-events: auto;
      bottom: 15px;
      position: relative;
    }
    .maplibregl-ctrl-basemaps.reverse {
      flex-direction: row-reverse;
    }
    .maplibregl-ctrl-basemaps.column {
      flex-direction: column;
    }
    .maplibregl-ctrl-basemaps.column.reverse {
      flex-direction: column-reverse;
    }
    .maplibregl-ctrl-basemaps .basemap {
      width: 64px;
      height: 64px;
      margin: 2px;
      border: 2px solid #ccc;
      box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
      cursor: pointer;
    }
    .maplibregl-ctrl-basemaps .basemap.active {
      border-color: orange;
      box-shadow: 2px 2px 4px #000;
    }
    .maplibregl-ctrl-basemaps.closed .basemap {
      display: none;
    }
    .maplibregl-ctrl-basemaps.closed .basemap.active {
      display: block;
      border: 2px solid #ccc;
    }
    CSS

Learn more

You can also use your custom maps in the styleSwitcherControl. Check out the How to display your custom map on the web page tutorial to learn how to get your map ID.

An extension of MapLibre GL JS