Leafletで「leaflet-locatecontrol」プラグインを導入して現在地表示機能を追加する方法
LeafletとOpenStreetMapでマップ表示させ、特定のアイコンをクリックすると現在地を表示し尚且つマーカーを設置したい。「leaflet-locatecontrol」プラグインを導入することで実装できた。尚、デフォルトのアイコンは微妙だったのでFont Awesomeのアイコンに変更する方法もあわせてメモ。
目次
leaflet-locatecontrol
GitHub
https://github.com/domoritz/leaflet-locatecontrol
デモページ
https://domoritz.github.io/leaflet-locatecontrol/demo/
CDN
CDNで使う場合は以下を記述する。
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-locatecontrol/0.79.0/L.Control.Locate.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-locatecontrol/0.79.0/L.Control.Locate.css">
Font Awesome
公式サイト
アイコンページ
CDN
CDNで使う場合は以下を記述する。
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
サンプル
https://taitan916.info/sample/leaflet.js/plugin/leaflet-locatecontrol/
マップ左上の「+」「-」ボタン下のアイコンをクリックすると現在地が表示される筈。
実装方法
ソースコード
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leafletで「leaflet-locatecontrol」プラグインを導入して現在地表示機能を追加するサンプル</title>
<style>
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
.leaflet-control-locate a.leaflet-bar-part span {
font-size: 1rem;
line-height: unset;
}
</style>
</head>
<body>
<div id="map"></div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-locatecontrol/0.79.0/L.Control.Locate.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-locatecontrol/0.79.0/L.Control.Locate.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<script>
let map;
map = L.map('map');
//中心の経度緯度
const center = ['35.681236', '139.767125'];
//ズームレベル
const zoom = 12;
//マップの中心地とズームレベルを指定
map.setView(center, zoom);
const tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 19
});
tileLayer.addTo(map);
//現在地表示
const option = {
position: 'topleft',
icon: 'fa-solid fa-location-dot',
strings: {
title: "現在地を表示",
popup: "現在地"
},
locateOptions: {
maxZoom: 16
}
}
const lc = L.control.locate(option).addTo(map);
</script>
</body>
</html>
関連記事
-
-
架空の地図画像をLeafletを用いてWeb上でマップ表示する方法
ゲーム攻略サイト等でゲーム内の地図をWeb上で表示し、マーカーを立てたりマウスホ ...
-
-
Leafletでマーカーをグループ化し、チェックボックスの状態により表示非表示を切り替える方法
LeafletとOpenStreetMapでマップ上にマーカーを複数設置した上で ...
-
-
Leafletで「sidebar-v2」プラグインを導入してマップ上にサイドバーを設置する方法
Leafletでマップ上にサイドバー及びサイドメニューを実装したい。調べたところ ...
-
-
Leafletにてマップ移動時にURLに座標を自動付与する「leaflet-view-meta」プラグインの利用方法
Googleマップだとマップを移動した際、URLに座標(経度緯度)が付与されるた ...
-
-
Leafletにて操作内容を履歴に残し「進む」「戻る」ボタンで履歴を実行できる「Leaflet.NavBar」の利用方法
Leafletにてマップ移動やズーム等、ユーザーの操作内容を履歴に残して、「進む ...