🎈

[GIS]MapLibre GL JS を使用し、Webマップ上でユーザーの現在地を特定する(備忘録)

2025/02/27に公開

1.はじめに

GISとは地理情報システム(Geographic Information System)の略称です。
・地球上に存在する地形物や事象をコンピュータ上の地図に可視化し、空間データの管理・検索・分析等を可能にします。

2.サンプルプログラム

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="style.css" rel="stylesheet" />
    <!-- MapLibre GL JS -->
    <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.1.0/dist/maplibre-gl.css' />
    <script src='https://unpkg.com/maplibre-gl@5.1.0/dist/maplibre-gl.js'></script>
</head>
<body>
    <!-- 地図を表示するHTML要素 -->
    <div id="map"></div>
    <script src="main.js"></script>
</body>
style.css
body { 
  margin: 0;
  padding: 0;
}

html,
body,
#map {
  height: 100%;
}
main.js
// 地図を初期化
const map = new maplibregl.Map({
    container: 'map', // 地図を表示するHTML要素のidを指定
    style: 'https://api.maptiler.com/maps/basic-v2/style.json?key=XXXXX',
    center: [139.767066, 35.6813],  // 地図表示開始位置(経度, 緯度) 
    zoom: 5 // ズームレベル
});

// 現在位置表示
map.addControl(
    new maplibregl.GeolocateControl({
        positionOptions: {
            // より精度の高い位置情報を取得する
            enableHighAccuracy: true
        },
        // ユーザーが移動するたびに位置を自動的に更新
        trackUserLocation: true
    })
);

・表示画面

3.実行環境

・OS: Windows 11(バージョン 24H2)
・ブラウザ: Microsoft Edge(バージョン 133.0.3065.82)
・エディタ: Visual Studio Code(バージョン 1.97)
・MapLibre GL JS: バージョン 5.1.0

4.参考

GISとは?メリットや活用例をわかりやすく解説
用語解説
Locate the user
MapLibre GL JS #017 - 現在位置の表示
スマホアプリ開発にも便利な位置情報API - Geolocation API -

Discussion