勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

leaflet.jsとOSMで現在地を取得しマップ上にマーカーを表示する方法

   2024/03/23  JavaScript

leaflet.jsとOpenStreetMapで現在位置の経度緯度を取得しマップ上にマーカーを設置したかった。以下にサンプルページと実装方法をメモ。

 

リファレンス

https://leafletjs.com/reference.html#map-locate

 

サンプル

https://taitan916.info/sample/osm/gps.php

 

ソース

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.js"></script> 
<script src="//code.jquery.com/jquery-latest.js"></script>
<script>
    var map = L.map('map_canvas');

    var tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
        attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 19
    });
    tileLayer.addTo(map);

    //現在地が取得できた場合の処理
    function gpsSuccess(e) {
        L.marker(e.latlng).addTo(map).bindPopup("現在地").openPopup();
    }

    //現在地が取得できなかった場合の処理
    function gpsError(e) {
        alert("現在地を取得できませんでした。" + e.message);
    }

    //現在地の取得
    map.locate({setView: true, maxZoom: 16, timeout: 20000});

    //成功した場合
    map.on('locationfound', gpsSuccess);

    //失敗した場合
    map.on('locationerror', gpsError);
</script>

 

注意点

GoogleMapAPIの時と同様に位置情報を取得するにはHTTPS接続の必要がある。例えば以下はサンプルと同じファイルだがHTTPS接続ではない為、位置情報が取得できない。

https://taitan916.info/sample/osm/gps.php

また、leaflet.jsをCDN呼び出しする場合は以下に変更する(前までの記事ではHTTPSが用意されていなかった)。

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.js"></script> 
<script src="//code.jquery.com/jquery-latest.js"></script>

 - JavaScript

  関連記事

Leafletでマーカーを動的に変更し、変更状況をCookieに保存する方法

Leafletでポップアップ(フキダシ)内のボタンをクリックするとマーカーを動的 ...

Leafletで表示したマップにジェスチャーハンドリングを追加する方法(Leaflet.GestureHandling)

GoogleMapをズームする際にPCだと「Ctrl+スクロール」、スマホだと「 ...

Leafletで「sidebar-v2」プラグインを導入してマップ上にサイドバーを設置する方法

Leafletでマップ上にサイドバー及びサイドメニューを実装したい。調べたところ ...

Leafletで「Leaflet.markercluster」プラグインを導入してマーカークラスタ機能を追加する方法

LeafletとOpenStreetMapでマップ上にマーカーを複数設置した上で ...

Leafletで「leaflet-control-geocoder」プラグインを導入して住所検索機能を追加する方法

LeafletとOpenStreetMapでマップを表示させ、テキストボックスに ...