Yuta NakataのBlog

Python / AWS / ITについて役立つ情報を発信します

Mapboxで複数のRaster Tileを同時にセットアップしたい。

やりたいこと

Mapboxを使って、複数のタイルデータを同時に表示したい。

ここでは、仮として表示したいタイルサーバーAを、 http://a.example.com/tiles/{z}/{x}/{y}.png

とし、

表示したいタイルサーバーBを、

http://b.hoge.com/tiles/{z}/{x}/{y}.png

とします。

できた方法

下記のコードで表示できました。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
    mapboxgl.accessToken = ''
    const map = new mapboxgl.Map({
        container: 'map', // container ID
        center: [-74.5, 40], // starting position
        zoom: 2 // starting zoom
    })
    
    map.addSource('source1', {
        type: 'raster',
        url: 'http://a.example.com/tiles/{z}/{x}/{y}.png'
    })
    
    map.addLayer({
        'id': 'data1',
        'type': 'raster',
        'source': 'source1',
        'source-layer': 'contour',
    })

    map.addSource('source2', {
        type: 'raster',
        url: 'http://b.hoge.com/tiles/{z}/{x}/{y}.png'
    });
    
    map.addLayer({
        'id': 'data2',
        'type': 'raster',
        'source': 'source2',
        'source-layer': 'contour',
    });
</script>
</script>

</body>
</html>

ポイントは、表示したいデータごとに、addSource,addLayerをすることです

だめなパターン

Mapboxの公式にあるような

"mapbox-streets": {
    "type": "vector",
    "tiles": [
        "http://a.example.com/tiles/{z}/{x}/{y}.pbf",
        "http://b.example.com/tiles/{z}/{x}/{y}.pbf"
    ],
    "maxzoom": 14
}

Tilesを複数指定するやり方はNGです。

これは、複数のタイルを表示するやり方ではなく、ひとつのデータに対して、冗長性を確保するようなものです

すなわち、

タイルサーバーAが死んだら、タイルサーバーBを見てね。

といった意味になりますので、2つのデータを表示できるわけではありません。