【MapLibre】ズームコントロール/コンパス/スケールを表示
上の図のように、マップの右上にズームコントロール/コンパスを追加するには、以下のように記述します(ナビゲーションコントロールを追加します)。なお、コンパスをクリックすると、北が上の表示に戻ります。
map.addControl(new maplibregl.NavigationControl({}), 'top-right');
左下にスケールバーを追加するには、以下のように記述します。
map.addControl(new maplibregl.ScaleControl(), 'bottom-left');
全体のソースコードは以下のようになります。
<!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; border:1px solid #333;'></div>
<!-- 以下OpenLayersのJavaScriptとCSS -->
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@3.4.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@3.4.0/dist/maplibre-gl.js'></script>
<script>
function init_map() {
const map = new maplibregl.Map({
container: 'mapcontainer',
style: {
version: 8,
sources: {
rtile: {
type: 'raster',
tiles: [
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
],
tileSize: 256,
attribution: '©<a href="https://www.openstreetmap.org/copyright/ja">OpenStreetMap</a> contributors',
},
},
layers: [{
id: 'raster-tiles',
type: 'raster',
source: 'rtile',
minzoom: 0,
maxzoom: 18,
}]
},
center: [142.14, 43.65],
zoom: 5,
pitch: 0
});
map.addControl(new maplibregl.NavigationControl({}), 'top-right');
map.addControl(new maplibregl.ScaleControl(), 'bottom-left');
}
//ダウンロード時に初期化する
window.addEventListener('DOMContentLoaded', init_map());
</script>
</body>
</html>
ちなみに、ズームコントロールのみ追加したい場合は、以下のように記述します。
map.addControl(new maplibregl.NavigationControl({showCompass:false}));
逆に、コンパスのみ追加したい場合は、以下のように記述します。
map.addControl(new maplibregl.NavigationControl({showZoom:false}));