Skip to content

Instantly share code, notes, and snippets.

@ywjno
Created August 26, 2021 15:26
Show Gist options
  • Save ywjno/ba2524a155ac1e12242cbbf3577b5093 to your computer and use it in GitHub Desktop.
Save ywjno/ba2524a155ac1e12242cbbf3577b5093 to your computer and use it in GitHub Desktop.
都道府県別日本地図(D3 + topojson)
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js" type="text/JavaScript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.20/topojson.min.js"></script>
</head>
<body>
<svg></svg>
<script>
var width = 1000,
height = 1000;
var scale = 1600;
d3.json(
"https://raw.githubusercontent.com/dataofjapan/land/master/japan.topojson",
createMap
);
function createMap(data) {
var japan = topojson.feature(data, data.objects.japan); // objects.japan であるかの確認必要
var aProjection = d3
.geoMercator()
.center([136.0, 35.6])
.translate([width / 2, height / 2])
.scale(scale);
var geoPath = d3.geoPath().projection(aProjection);
var svg = d3.select("svg").attr("width", width).attr("height", height);
//マップ描画
var map = svg
.selectAll("path")
.data(japan.features)
.enter()
.append("path")
.attr("d", geoPath)
.style("stroke", "#ffffff")
.style("stroke-width", 0.1)
.style("fill", "#5EAFC6");
//ズームイベント設定
var zoom = d3.zoom().on("zoom", function() {
aProjection.scale(scale * d3.event.transform.k);
map.attr("d", geoPath);
});
svg.call(zoom);
//ドラッグイベント設定
var drag = d3.drag().on("drag", function() {
var tl = aProjection.translate();
aProjection.translate([tl[0] + d3.event.dx, tl[1] + d3.event.dy]);
map.attr("d", geoPath);
});
map.call(drag);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment