前回の続き.
ブラウザに地図を表示するところまで.
HTML
ほとんどを動的に生成できるからほぼ何もいらない
d3.js
とtopojson.js
の二つを読み込むことだけ忘れないように.
index.html
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset="utf-8">
<title>Tokyo sample</title>
<script src='http://d3js.org/d3.v3.min.js' charset="utf-8"></script>
<script src='http://d3js.org/topojson.v0.min.js'></script>
</head>
<body>
<h1>D3.js Tokyo</h1>
<script type="text/javascript" src="js/tokyo.js"></script>
</body>
</html>
javascript
d3.json()
でファイルを読み込んで,
2行目でtopojsonの大事なところに
$ less tokyo_honshu.topojson
{"type":"Topology","objects":{"tokyo_honshu":{"type":"GeometryCollection","geometries":[{"type":"Polygon","properties":{"shi":"奥
多摩町","ku":"西多摩郡"},"id":"13308","arcs":[[0,1,2,3]]},{"type":"Polygon"
json.objects.tokyo_honshu
でアクセス.
あとは地図をどこに表示するか,とか大きさをどうするかっていう設定をしたりする.
tokyo.js
var w = 1000;
var h = 1000;
var svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h);
d3.json('../data/modify_data/tokyo_honshu.topojson', function(json) {
var tokyo = topojson.object(json, json.objects.tokyo_honshu).geometries;
var projection = d3.geo.mercator()
.center([139.532454, 35.723002])
.translate([w/2-150, h/2-350])
.scale(30000);
var path = d3.geo.path().projection(projection);
svg.selectAll("path")
.data(tokyo)
.enter()
.append("path")
.attr("d", path)
});
さらに線をひいて,色をぬる.
ホバーもできるようにしておく.
tokyo.js
svg.selectAll("path")
.data(japan)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "black") // 追加
.attr("stroke-width", 0.5) // 追加
.attr('class', function(d) { // 追加
return 'area areatokyo'; // 追加
}) // 追加
スタイルシートも追加
CSSでもいいとは思うけども.
index.html
<style type="text/css">
.area {stroke: #000000;}
.areatokyo {fill: #ddd;}
.area:hover {fill: #00ffff;}
</style>
さらにクリックした時にその場所の名前をだす.
index.html
<h3 id="cityname">場所:</h3>
tokyo.js
svg.selectAll("path")
.data(japan)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "black")
.attr("stroke-width", 0.5)
.attr('class', function(d) {
return 'area areatokyo';
}) // 以下追加
.attr('data-cityname', function(d) {
// console.log(d.properties.name)
if (d.properties.ku) {
return d.properties.ku
}
return d.properties.shi
})
.on('click', function() {
var self = d3.select(this);
d3.select('#cityname').text("場所: " + self.attr('data-cityname'))
})
これでクリックしたところの名前が出る
もし地図上に表示したいなら以下を追加
tokyo.js
svg.selectAll(".place-label")
.data(japan)
.enter()
.append("text")
.attr("font-size", "8px")
.attr("class", "place-label")
.attr("transform", function(d) {
return "translate(" + path.centroid(d) + ")";
})
.attr("dx", "-1.5em")
.text(function(d) {
if (d.properties.ku) {
return d.properties.ku;
}
return d.properties.shi;
});
参考というかほぼコピペ
http://kshigeru.blogspot.jp/2013/03/d3-geojson-polygon.html
http://ja.d3js.node.ws/blocks/mike/map/