Skip to content

Instantly share code, notes, and snippets.

@shimizu
Last active November 1, 2019 08:28
Show Gist options
  • Save shimizu/2858b601b8c475e99d081e173a53cf8a to your computer and use it in GitHub Desktop.
Save shimizu/2858b601b8c475e99d081e173a53cf8a to your computer and use it in GitHub Desktop.
leaflet@1.5.1 & d3@5.0.0 - ポリゴン表示表示

leaflet@1.5.1 と d3@5.0.0 を使って地図上にポリゴンを表示するサンプル

<!DOCTYPE html>
<html>
<head>
<title>Leafletv1.5.1 + D3v5 point</title>
<meta charset="utf-8" />
<!-- leafletのcssを読み込む -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
<!-- leafletのスクリプトを読み込む-->
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""></script>
<style>
html,
body,
#map {
width: 100%;
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- D3.js ver.5 を読み込む-->
<script src='//unpkg.com/d3@5.0.0/dist/d3.min.js'></script>
<script>
//Leaflet初期設定
var map = L.map('map').setView([39.702053, 141.15448379999998], 5);
var mapLink = '<a target="_blank" href="http://portal.cyberjapan.jp/help/termsofuse.html">国土地理院 地理院地図 標準地図</a>';
//Leafletにsvgレイヤーを追加
L.svg().addTo(map);
//Tile Map Serviceの指定
L.tileLayer('http://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
attribution: '&copy; ' + mapLink + ' Contributors',
maxZoom: 18
}).addTo(map);
d3.json('pref.geojson').then(drawMap);
function drawMap(geojson) {
// svg要素を選択
var svg = d3.select('#map').select('svg');
var g = svg.append('g');
//緯度経度->パスジェネレーター関数作成
//位置→座標変換
var projectPoint = function (x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
};
var transform = d3.geoTransform({ point: projectPoint });
var path = d3.geoPath().projection(transform);
featureElement = g
.selectAll('path')
.data(geojson.features)
.enter()
.append('path')
.attr('stroke', 'red')
.attr('fill', 'green')
.attr('fill-opacity', 0.4);
//pathのd属性を更新
var update = function () {
featureElement.attr('d', path);
};
map.on('moveend', update);
update();
}
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment