Leafletで地図を実装するデモ(2)

チュートリアルの2番目となるiPhone,iPad,Android系のようなモバイル端末向けにフルスクリーンの地図を実装してみます。

今回の完成形はこちら。
デモ

まず初期化処理と地図のスタイルを定義して画面全体に表示されるようにします。

body {
  padding: 0;
  margin: 0;
}
html, body, #mapid {
  height: 100%;
  widht: 100vw;
}

次にviewportを設定して画面表示を制御します。

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

次にJavaScriptのコードを埋め込みます。

// マップオブジェクト生成
var mymap = L.map('mapid').fitWorld();

// データソースは国土地理院
L.tileLayer(
    'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
        attribution: '© 地理院タイル'
    }).addTo(mymap);

// 位置情報検索
mymap.locate({setView: true, maxZoom: 10});

// 位置情報取得成功処理
function onLocationFound(e) {
    var radius = e.accuracy / 2;
    L.marker(e.latlng).addTo(map)
        .bindPopup("You are within " + radius + " meters from this point").openPopup();

    L.circle(e.latlng, radius).addTo(map);
}
mymap.on('locationfound', onLocationFound);

// 位置情報取得エラー処理
function onLocationError(e) {
    alert(e.message);
}
mymap.on('locationerror', onLocationError);

以上でモバイル端末に最適化したサンプルの作成が完了です。
デモページのソースは以下となります。
デモ

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Leafletチュートリアル</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"
integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
crossorigin=""></script>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #mapid {
height: 100%;
widht: 100vw;
}
</style>
</head>
<body>
<div id="mapid"></div>
<script>
// マップオブジェクト生成
var mymap = L.map('mapid').fitWorld();
// データソースは国土地理院
L.tileLayer(
'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://maps.gsi.go.jp/development/ichiran.html" target="_blank">地理院タイル</a>'
}).addTo(mymap);
// 位置情報検索
mymap.locate({setView: true, maxZoom: 10});
// 位置情報取得成功処理
function onLocationFound(e) {
var radius = e.accuracy / 2;
// マーカーを表示
L.marker(e.latlng).addTo(mymap)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
// サークルを表示
L.circle(e.latlng, radius).addTo(mymap);
}
mymap.on('locationfound', onLocationFound);
// 位置情報取得エラー処理
function onLocationError(e) {
alert(e.message);
}
mymap.on('locationerror', onLocationError);
</script>
</body>
</html>
目次

参考

Leaflet on Mobile
https://leafletjs.com/examples/mobile/

よかったらシェアしてね!
  • URLをコピーしました!
目次