跳轉到

Getting started with MapLibre GL⚓︎

Introduction⚓︎

MapLibre GL JS is a TypeScript library that uses WebGL for embedding maps. It uses a permissive BSD open-source license so can be incorporated into any site without legal worries. Its source code is available on GitHub.

Here, we restrict ourselves to a small, self-contained example and refer to the official tutorials and documentation for elaborate usages.

Getting started⚓︎

Displaying a map requires three things: a data source, map style, and site to host them all. We're going to use the OpenStreetMap Foundation Shortbread tiles, the Versatiles Colorful style, and a website you'll run.

Hosting

Some browser features require a page is served from a secure location. This is a website with HTTPS or your local computer. We're assuming you have a web host for "example.com" that lets you serve files from disk and that you know how to copy files to the web host.

Software Installation⚓︎

We need Node.js 18 or later. If you have Ubuntu 24.04 or later or Debian 12 or later, you can install these with

sudo apt-get install nodejs

For other operating systems consult their documentation. You can check the version of Node.js you have with node --version. If it's below 18 you will need to install your own version of Node. One way to do this is with nvm.

Building the style⚓︎

We're going to be using the VersaTiles colorful style, a basic style which uses Shortbread tiles. The Shortbread vector tile schema is a general-purpose vector tile schema for OpenStreetMap data. To get the tiles we're going to use the OpenStreetMap Foundation's Shortbread tile service.

Usage of the vector tiles is governed by the vector tile usage policy. This web page will meet the requirements, but there is no SLA or guarantee with the vector tile service. If you need these you should host them yourself or use a commercial host.

A style requires a style definition and sprite files for any icons. We're going to build the style definition to point to our own sprites.

Start by making a new directory to store the files you'll be creating. We'll call it "style" in the documentation, but it can be whatever you want. Inside this directory we're going to build all the files we need and place them in a "release" subdirectory

mkdir style
cd style
mkdir release

Building sprites can be a complicated process, but because we don't need to modify them we're going to use pre-built ones

curl -OL https://github.com/versatiles-org/versatiles-style/releases/download/v5.10.0/sprites.tar.gz
mkdir -p release/sprites
tar -C release/sprites -xzf sprites.tar.gz

We now need to build the style so it uses our new copy of the sprites and the OSMF vector tile service.

Copy the following content to a file build.ts, but change "example.com" to the URL that you will serve the tiles from, including your domain name

build.ts
import { colorful } from "@versatiles/style";
import { writeFileSync } from "node:fs";

const style = colorful({
    baseUrl: "https://example.com",
    fonts: { regular: "Noto Sans", bold: "Noto Sans Bold" },
    sprite: [{ id: 'basics', url: "/sprites/basics/sprites" }],
    tiles: ["https://vector.openstreetmap.org/shortbread_v1/{z}/{x}/{y}.mvt"]
});

// We're using web fonts so we don't need glyphs
delete style.glyphs;
writeFileSync("release/style.json", JSON.stringify(style));

In the same directory install TypeScript and the VersaTiles styles, then run the script above to build your style.

npm install tsx @versatiles/style@~5.10.0
node_modules/.bin/tsx build.ts

Copy the following content to a file maplibre.html and put it in the release directory

maplibre.html
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap" rel="stylesheet">
  <script src='https://unpkg.com/maplibre-gl@5.21/dist/maplibre-gl.js'></script>
  <link href='https://unpkg.com/maplibre-gl@5.21/dist/maplibre-gl.css' rel='stylesheet' />

  <style>
    #map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
  </style>
</head>
<body>
  <div id="map"></div>
  <script>
    // Pre-load the fonts
    const fonts = ["Noto Sans", "Noto Sans Bold"];
    Promise.all(fonts.map(font => {
      try {
        return document.fonts.load(`24px '${font}'`);
      } catch (e) {
        // Swallow any font loading error so the map keeps loading
      }
    })).then(() => {
      maplibregl.setRTLTextPlugin(
          'https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.4.0/dist/mapbox-gl-rtl-text.js',
          true // Lazy load the plugin
      );

      const map = new maplibregl.Map({
        style: new URL('style.json', window.location.href).href,
        container: 'map',
        center: [0, 0],
        zoom: 1,
        hash: true,
        maxZoom: 19
      });
  });
  </script>
</body>
</html>

Releasing the style⚓︎

Copy the contents of the "release" directory to the location that you chose earlier, that you will serve the files from. Common ways of doing this are with a scp or rsync command, or through a web interface.

Common problems⚓︎

node_modules/.bin/tsx build.ts fails to run⚓︎

If you have an outdated version of node, this command will fail to run. You can fix this by installing an up-to-date version with nvm as described earlier.

Nothing loads on the web page⚓︎

Open your browser's Developer Tools and look at the console. The most common cause of nothing displaying is incorrect URLs.