【MapLibre】マップにマーカーを追加する

 MapLibre でマップにマーカーを追加するだけなら、下記の1行を追加するだけで大丈夫です。

const marker = new maplibregl.Marker().setLngLat([経度, 緯度]).addTo(map);

 マーカーの色も簡単に変えられます。便利ですね。

const marker = new maplibregl.Marker({color:'#ff0000'}).setLngLat([経度, 緯度]).addTo(map);

 ポップアップを追加するには、別途ポップアップを定義して、マーカーにセットするだけです。ここでは、右上にある閉じるボタンが邪魔なので、closebutton: false としました。

const popup = new maplibregl.Popup({offset: 25, closeButton: false}).setText(テキスト);
marker.setPopup(popup);

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

<!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 
    });

    const marker = new maplibregl.Marker({color: '#ff0000'}).setLngLat([142.14, 43.65]).addTo(map);

    const popup = new maplibregl.Popup({offset: 25, closeButton: false}).setText('北海道');
    marker.setPopup(popup);
}

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

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


 ちなみに、マーカーのクリックイベントはポップアップが登録してあるため、マーカーにクリックイベントを付加しようと思うと、マーカークラスをオーバーライドする必要が有ります。リンクを貼るぐらいのイベントだったら、ポップアップにリンクを仕込んでおいた方が無難ですね。

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です