パントレ開発部

【Leaflet】複数のマップタイルを切り替える

Map

はじめに

 OpenStreetMap や国が公開しているデータなど、マップには様々なオープンデータが存在します。今回はそれらマップタイルを切り替える方法のうち、 ①コントロールを追加して切り替える方法、および ②外部から切り替える方法の2つについてまとめます。

パントレ

 なお、この記事は「【Leaflet入門】地図を表示する方法と基本的な使い方」の続きです。
 

コントロールを追加する方法

 コントロールを追加してマップタイルを切り替える方法について説明します。

 まずコントロールに追加するタイルレイヤーを定義します。複数のタイルを引用していますが、それぞれの利用方法については概要を別のページにまとめています。

//最初に表示させるタイルに addTo(map) をつける
const OSMtile = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors'
}).addTo(map); 

const HOTtile = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
    attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, Tiles: <a href="http://map.hotosm.org/" target="_blank">©HOT</a>'
});

const OTMtile = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
    attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org/" target="_blank">SRTM</a> | map style: <a href="https://opentopomap.org/" target="_blank">©OpenTopoMap</a>'
});

 次に、定義したタイルレイヤーをコントロールに紐づけます。

L.control.layers({
    "OpenStreetMap": OSMtile,
    "Humanitarian map style": HOTtile,
    "OpenTopoMap": OTMtile
}).addTo(map); 

 以上まとめると、全体のソースコードと実装例は以下のようになります。

<!DOCTYPE html>
<html>
<head>
<title>htmlMap</title>
<meta http-equiv='content-type' charset='utf-8'>
<meta name='viewport' content='width=device-width'>
</head>
<body>
<!-- 埋め込みマップのdivタグ。マップサイズはwidth(幅)とheight(高さ)で決まる -->
<div id='mapcontainer' style='width:100%; height:300px; z-index:0;'></div>
<!-- 以下LeafletのJavaScriptとCSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- ダウンロードしたFont Awesomeへのファイルパス -->
<link href="css/font-awesome.min.css" rel="stylesheet">

<script>
function init_map() {
    const map = L.map('mapcontainer');

    //初期の中心位置とズームレベルを設定
    map.setView([39.198, 138.603], 3); 

    //最初に表示させるタイルに addTo(map) をつける
    const OSMtile = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors'
    }).addTo(map); 

    const HOTtile = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
        attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, Tiles: <a href="http://map.hotosm.org/" target="_blank">©HOT</a>'
    });

    const OTMtile = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
        attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org/" target="_blank">SRTM</a> | map style: <a href="https://opentopomap.org/" target="_blank">©OpenTopoMap</a>'
    });
    
    L.control.layers({
        "OpenStreetMap": OSMtile,
        "Humanitarian map style": HOTtile,
        "OpenTopoMap": OTMtile
    }).addTo(map); 
}

//ダウンロード時に初期化する
window.addEventListener('DOMContentLoaded', init_map());

</script>
</body>
</html>

実装例

 

外部から切り替える方法

 次に、ボタンやプルダウンメニューなど、外部の要素から Leaflet のマップタイルを切り替える方法について説明します。

 まず、remove(map) で現在設定しているタイルレイヤーを削除します。

tileLayer.remove(map);

  次に、addTo(Map) で設定したいタイルレイヤーをマップに貼りなおします。

tileLayer.addTo(map);

 以上のようにして、プルダウンメニューからタイルを切り替えられるようにしてみました。このとき全体のソースコードと実装例は以下のようになります。

<!DOCTYPE html>
<html>
<head>
<title>htmlMap</title>
<meta http-equiv='content-type' charset='utf-8'>
<meta name='viewport' content='width=device-width'>
</head>
<body>
<div id='mapcontainer' style='width:100%; height:300px; z-index:0;'></div>
<select id="tileSelect">
    <option value="0" selected>OpenStreetMap</option>
    <option value="1">Humanitarian map style</option>
    <option value="2">OpenTopoMap</option>
</select>
<!-- 以下LeafletのJavaScriptとCSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- ダウンロードしたFont Awesomeへのファイルパス -->
<link href="css/font-awesome.min.css" rel="stylesheet">

<script>
function init_map() {

    //タイル情報を格納した配列
    const mapTile = [
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors'}),
        L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, Tiles: <a href="http://map.hotosm.org/" target="_blank">©HOT</a>'}),
        L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
            attribution: '<a href="https://www.openstreetmap.org/copyright" target="_blank">©OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org/" target="_blank">SRTM</a> | map style: <a href="https://opentopomap.org/" target="_blank">©OpenTopoMap</a>'})
    ];

    let currentTile = 0;

    const map = L.map('mapcontainer');

    //初期の中心位置とズームレベルを設定
    map.setView([39.198, 138.603], 3);

    //マップタイルの初期値を設定
    mapTile[currentTile].addTo(map);

    //セレクトボックスに onchange イベントを追加
    document.getElementById('tileSelect').onchange = function() {
        mapTile[currentTile].remove(map);
        currentTile = document.getElementById("tileSelect").value;
        mapTile[currentTile].addTo(map);
    }
}

//ダウンロード時に初期化する
window.addEventListener('DOMContentLoaded', init_map());

</script>
</body>
</html>

実装例

 

関連記事

 GUI で Leaflet の HTML/JavaScript を生成するツールはこちら。コード書くのがめんどくさいな~って人は使ってみてください。WordPress の場合、生成されたコードをカスタム HTML に貼り付ければ動きます。

 Leaflet、MapLibre、OpenLayers の比較はこちら。

 MapLibre についてはこちら。

 

ちょっと宣伝

 当サイトは Web 地図を積極的に用いた海外旅ブログまとめサイトとなっています。トップページに地図がありますが、地名を押すと画像が開き、画像を押すと関連記事一覧(クリック数順)が開きます。記事数が多い国ほど赤く、地名もその国で記事が多い都市の文字が大きくなるようにしています。ぜひ覗いてみてください。
 当サイトで海外旅ブログを執筆することも可能です(もちろん無料です)! また既にブログをお持ちの方も、当サイトからリンクを貼ることができるようになっています。パントレ開発部までお気軽にお問い合わせください。


 このページが皆様のプログラミングの一助となりますことをお祈りいたします

パントレ開発部