background image
MapLibre GL JS

MapLibre GL JSのラベル表示の小技(単位をつける、数値の丸め)

cover image from Unsplash

Photo by Annie Williams on Unsplash

本記事について

MapLibre GL JS のラベル表示において、よく使う式演算子を紹介する。

基本となるソースコード

地図はMapLibre Demo Tilesを使用した。

ラベルはsymbolタイプのレイヤのtext-fieldプロパティで設定できる。
今回表示する値は、sourceに指定した geojson のareaプロパティとした。

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <script src="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.js"></script>
    <link href="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css" rel="stylesheet" />
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      html,
      body,
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      const map = new maplibregl.Map({
        container: "map",
        // https://github.com/maplibre/demotiles
        style: "https://demotiles.maplibre.org/style.json",
        center: [136, 37],
        zoom: 5,
      });

      map.on("load", () => {
        map.addSource("rectangle", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: [
              {
                type: "Feature",
                geometry: {
                  type: "Polygon",
                  coordinates: [
                    [
                      [135, 39],
                      [135, 35],
                      [140, 35],
                      [140, 39],
                      [135, 39],
                    ],
                  ],
                },
                properties: {
                  area: 1234.5,
                },
              },
            ],
          },
        });
        map.addLayer({
          id: "rectangle",
          type: "fill",
          source: "rectangle",
          paint: {
            "fill-color": "white",
            "fill-opacity": 0.7,
          },
        });
        map.addLayer({
          id: "rectangle-label",
          type: "symbol",
          source: "rectangle",
          layout: {
            "text-field": ["get", "area"],
          },
        });
      });
    </script>
  </body>
</html>

Image from Gyazo

値に単位をつける

concat演算子でラベルの末尾に単位をつけることができる。
areaプロパティは数値だが、concatで自動的に文字列に変換され、他の文字列と結合される。

https://maplibre.org/maplibre-style-spec/expressions/#concat

index.html
// (省略)
map.addLayer({
  id: "rectangle-label",
  type: "symbol",
  source: "rectangle",
  layout: {
    "text-field": ["concat", ["get", "area"], " km²"],
  },
});
// (省略)

Image from Gyazo

数値を丸めて表示(四捨五入)

round演算子で整数に丸めることができる。
丸めた後はto-stringで文字列に変換する必要があるので注意。

https://maplibre.org/maplibre-style-spec/expressions/#round

index.html
// (省略)
map.addLayer({
  id: "rectangle-label",
  type: "symbol",
  source: "rectangle",
  layout: {
    "text-field": ["to-string", ["round", ["get", "area"]]],
  },
});
// (省略)

Image from Gyazo