勉強したことのメモ

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.jsとOSMでマーカーの画像をそれぞれ指定する

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

leaflet.jsとOSMでマップ表示及びマーカー設置方法

GoogleMapAPIを用いたマップ及びマーカー表示にクレジットカード登録が必 ...