Leaflet Quick Start Guide: GeoJSON の利用
本ページは,leaflet のチュートリアルの Using GeoJSON with Leaflet を日本語で簡単にまとめたものである.
GeoJSON
GeoJSON は JavaScript Object Notation (JSON) を用いて空間データをエンコードし, 非空間属性を関連付けるファイルフォーマットである. 属性にはポイント(住所や座標),ライン(各種道路や境界線), ポリゴン(国や地域)などが含まれる.
例えば,とある位置 (緯度経度) で得られた温度データは以下のように表現される.
var someGeojsonFeature = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"temp": 20
},
"geometry": {
"type": "Point",
"coordinates": [133.026, 35.50]
}
},
{
"type": "Feature",
"properties": {
"temp": 40
},
"geometry": {
"type": "Point",
"coordinates": [133.027, 35.488]
}
}
]
};
プロット方法
サークルを書く場合は,以下のように GeoJSON を読み込めば良い.
L.geoJson(someGeojsonFeature, {
pointToLayer: function (feature, latlng) {
return L.circle(latlng, 50, {color: 'red'})
}
}).addTo(mymap);
温度に応じて色を変える場合は if 文が使える.
L.geoJson(someGeojsonFeature, {
pointToLayer: function (feature, latlng) {
if (feature.properties.temp >= 30) {
return L.circle(latlng,50, {color: 'red'})
}
if (feature.properties.temp < 30) {
return L.circle(latlng,50, {color: 'blue'})
}
}
}).addTo(mymap);
まとめ
以下のような HTML を作成すると, 松江高専付近の地図に温度に応じた 2 つの色違いのサークルが表示されるはずである. <URL:leaflet-samples/> の leaflet-03.html をダウンロードして用いてみよ.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex" />
<title>Leafletチュートリアル</title>
<!-- Leaflet's CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<!-- Leaflet JavaScript file -->
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"
integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
crossorigin=""></script>
<style>
#mapid { height: 600px; }
</style>
</head>
<body>
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([35.495897, 133.025808], 15);
// データソースは国土地理院
L.tileLayer(
'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
attribution: '© <a href="https://maps.gsi.go.jp/development/ichiran.html" target="_blank">地理院タイル</a>'
}).addTo(mymap);
// geoJson で緯度経度, およびその地点の温度の指定
var someGeojsonFeature = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"temp": 20
},
"geometry": {
"type": "Point",
"coordinates": [133.026, 35.50]
}
},
{
"type": "Feature",
"properties": {
"temp": 40
},
"geometry": {
"type": "Point",
"coordinates": [133.027, 35.488]
}
}
]
};
L.geoJson(someGeojsonFeature, {
pointToLayer: function (feature, latlng) {
if (feature.properties.temp >= 30) {
return L.circle(latlng,50, {color: 'red'})
}
if (feature.properties.temp < 30) {
return L.circle(latlng,50, {color: 'blue'})
}
}
}).addTo(mymap);
</script>
</body>
</html>