Leaflet.js で地図を表示してみる
Leaflet は広く使われているWeb地図のためのJavaScriptライブラリである。
ためしで、地図を表示してみた。
[html]
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>Leaflet TEST</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<script>
//. 掛川城の緯度経度(初期位置)
var lat = 34.77530283508074;
var lng = 138.01500141620636;
var map = null;
var marker = null;
$(function() {
//. 掛川城を中心とした地図を OpenStreetMap データで表示
map = L.map('map’).setView([lat, lng], 15);
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, {
attribution: 'Map data © <a href="http://openstreetmap.org/">OpenStreetMap</a>’,
maxZoom: 18
}
).addTo(map);
//. 初期状態で掛川城にマーカーを設置
var mapMarker = L.marker([34.77530283508074, 138.01500141620636]).addTo(map);
var comment = 'sample <br> 掛川城’;
mapMarker.bindPopup(comment);
});
</script>
<style>
html,
body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
[/html]
これでページ上部のようなMAPを表示することができる。
表示する地図の種類に関しては
21行目
[html]’http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'[/html]
の部分を
[blogcard url="https://qiita.com/nyampire/items/fbe359a2c9ccf0116787″]
を参考に変更することができる。
それに併せてコピーライト部分も変更の必要あり
[html]attribution: 'Map data © <a href="http://openstreetmap.org/">OpenStreetMap</a>’,[/html]
また、ThunderForest
[blogcard url="https://www.thunderforest.com/"]
のタイルを使用する場合は、APIキーを取得して
[html][/html]https://tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=取得したAPIキー[html][/html]
と指定する必要がある。