[Gist] https://gist.github.com/Hirosaji/bf521aff2c54f88d96d1424397c87916
Built with blockbuilder.org
# Turf.js × Leaflet.js × D3.js - Square Grid on Map | |
license: mit |
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta http-equiv="content-language" content="ja"> | |
<title>Chiba McDonald's Map</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.3/leaflet.css"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.3/leaflet.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.js"></script> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
#map { | |
width: 100%; | |
height: 500px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
//jsonデータの読み込み | |
d3.queue() | |
.defer(d3.json, 'chibaMacMap.geojson') | |
.defer(d3.json, 'chibaChoroplethMap.geojson') | |
.await(function(error, points, geojson) { | |
map = L.map('map').setView([35.6, 140.15], 12); | |
//地理院地図レイヤー追加 | |
L.tileLayer( | |
'http://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png', | |
{ | |
attribution: "<a href='http://www.gsi.go.jp/kikakuchousei/kikakuchousei40182.html' target='_blank'>国土地理院</a>", | |
accessToken: 'pk.eyJ1IjoiaGlyb3NhamkiLCJhIjoiY2phYW1qM2lyMHRzcTMybzd1dzhlaG83NCJ9.2QcsoUxneas4TQFI3F-DyQ', | |
maxZoom: 18, | |
} | |
).addTo(map); | |
// コロプレス図の配置 | |
L.geoJson(geojson).addTo(map); | |
//マーカークリック時にポップアップを表示 | |
var onEachFeature = function(feature, layer) { | |
layer.bindPopup(feature.properties.name); | |
} | |
//マーカーを地図に追加 | |
var markerLayer = L.geoJson(points, { onEachFeature: onEachFeature }).addTo(map); | |
//squareグリッド用のレイヤーを準備 | |
var squareLayer = L.geoJson().addTo(map); | |
//表示されている四隅の緯度経度を取得 | |
var b = map.getBounds(); | |
extend = [b.getSouthWest().lng , b.getSouthWest().lat , b.getNorthEast().lng, b.getNorthEast().lat]; | |
//表示されている範囲をsquareで埋める | |
var grid = turf.squareGrid(extend, 2, {units: 'kilometers'}); | |
//squareデータに統計情報を付加(今回はマーカーの数のみ) | |
var grid = turf.collect(grid, points, 'value', 'values'); | |
//各セルのスタイルを設定 | |
grid.features.forEach(setStyle); | |
//squareグリッドを地図に追加 | |
squareLayer.addData(grid); | |
//統計情報に合わせてsquareグリッドのスタイルを調整 | |
squareLayer.eachLayer(function(l) { | |
l.setStyle(l.feature.properties.withSum); | |
}); | |
}); | |
//各セルのスタイルを指定 | |
function setStyle(cell){ | |
cell.properties.withSum= {}; | |
var pt_sum = cell.properties.values.length; | |
var _withSum = {}; | |
_withSum.color = '#FF0000'; | |
_withSum.weight = 0; | |
_withSum.fill = '#FF0000'; | |
_withSum.fillOpacity = 0; | |
if(pt_sum >= 1) { | |
_withSum.fillOpacity = 0.1; | |
} if(pt_sum >= 2) { | |
_withSum.fillOpacity = 0.3; | |
_withSum.weight = 1; | |
} if(pt_sum >= 3) { | |
_withSum.weight = 2; | |
_withSum.fillOpacity = 0.6; | |
} if(pt_sum >= 4) { | |
_withSum.weight = 3; | |
_withSum.fillOpacity = 0.9; | |
} | |
cell.properties.withSum = _withSum; | |
} | |
</script> | |
</html> |