LoginSignup
6
1

LWC と Leaflet.js でマップを表示してみよう!

Last updated at Posted at 2023-12-04

皆様、お久しぶりです!
今回は、LWC で Leaflet.js というオープンソースの地図表示系 JavaScript ライブラリを使う機会があったので備忘録も兼ねて紹介してみたいと思います。

Leaflet.js の取り込み

まずは、作成済みの sfdx プロジェクトに Leaflet.js のライブラリを取り込んで、静的リソースとして追加します。

$ sf static-resource generate -n LEAFLET -d force-app/main/default/staticresources
$ npm install leaflet
$ cp -r node_modules/leaflet/dist/* force-app/main/default/staticresources/LEAFLET
$ npm uninstall leaflet

ライブラリの取り込みには、公式サイトからダウンロードしてきても問題ありませんが、ここでは NPM を使ってインストールしたものを静的リソースに移動して使っています。ライブラリ自体はNPMに管理してもらう必要がないので、静的リソースへの複製後、アンインストールしてます。

マップ表示コンポーネントを作成する

それでは早速、Open Street Map のタイルレイヤーを使って、シンプルなマップを表示してみましょう。

mapComponent.html
<template>
    <div class="map" lwc:dom="manual"></div>
</template>
mapComponent.js
import { LightningElement } from "lwc";
import LEAFLET from "@salesforce/resourceUrl/LEAFLET";
import { loadStyle, loadScript } from "lightning/platformResourceLoader";
export default class LeafletMap extends LightningElement {
  isResourceLoaded;

  renderedCallback() {
  
    // DOM にアクセスする必要があるので、
    // 描画の完了を待って一度だけリソースを読み込む
    if (!this.isResourceLoaded) {
      Promise.all([
        loadScript(this, LEAFLET + "/leaflet.js"),
        loadStyle(this, LEAFLET + "/leaflet.css")
      ]).then(() => {

        // リソースが読み込まれたらフラグを立てる
        this.isResourceLoaded = true;

        // マップを初期化
        const mapContainer = this.template.querySelector(".map");
        const map = L.map(mapContainer).setView([35.684505, 139.76257], 16);

        // Open Street Map のタイルレイヤーを表示
        L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
          attribution:
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);
      });
    }
  }
}
mapComponent.css
.map {
  height: 600px;
  z-index: 0;
}

組織にデプロイ後、ページに配置してみましょう。
こんな感じで表示されれば成功です。
Screenshot 2023-11-27 at 10.02.38.png

タイルレイヤーの変更

タイルレイヤーを変更することで、Open Street Map が提供するマップ以外のマップを利用して見た目を変えることができます。以下の Leaflet Providers からどんなマップが提供されているかプレビューすることもできます

ここでは ArcGIS で提供されるマップを読み込んてみます。

mapComponent.js(抜粋)
L.tileLayer(
          "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}",
          {
            attribution:
              "Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community"
          }
        ).addTo(map);

その結果、表示されるのがこちらのマップです。

Screenshot 2023-11-27 at 10.09.45.png

最後に

いかがでしょうか。
マップの表示ソリューションにはいくつかのライブラリが存在していますが、LWC では利用できないものをあるので、要件に合えばぜひ、Leaflet.js の利用も検討してみてください。

6
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1