前回の続き。
D3.jsを使ってジオデータのビジュアライズができることを目指した第2回勉強会のまとめ。
東京都の地図の各市区町村にマウスオーバー・クリックで色を変えるところまで。
前回のまとめ
ほとんどsawamur@githubの投稿のまま。
mapping.js
var g,
width = 900,
height = 400;
var base_fill_color = "rgb(150,150,150)",
base_stroke_color = "rgb(30,30,30)";
// svg要素を作成し、データの受け皿となるg要素を追加している
map = d3.select('#map').append('svg')
.attr('width', width)
.attr('height', height)
.append('g');
// 同じディレクトリにあるgeojsonファイルをhttp経由で読み込む
d3.json("tokyo.geojson", function(json) {
var projection,
path;
var map_id;
// 投影を処理する関数を用意する。データからSVGのPATHに変換するため。
projection = d3.geo.mercator()
.scale(25000)
.center(d3.geo.centroid(json)) // データから中心点を計算
.translate([width*2, -height/1.3]);
// pathジェネレータ関数
path = d3.geo.path().projection(projection);
// これがenterしたデータ毎に呼び出されpath要素のd属性に
// geoJSONデータから変換した値を入れる
map.selectAll('path')
.data(json.features)
.enter()
.append('path')
.attr('id',function(d){
map_id = d.properties.N03_001+"_"+d.properties.N03_004;
return(map_id);
})
.attr('d', path)
.attr("stroke", base_stroke_color)
.attr("fill", base_fill_color)
});
マウスオーバーで色を変える
マウスオーバーしたポリゴンの中の色・線の色を変える。
.on('mouseover', function(d){}
部分に以下を記述
mapping.js
//マウスオーバー時のインタラクション
.on('mouseover', function(){
this.attributes['stroke'].value = "yellow";//線の色を黄色
this.attributes['fill'].value = "red";//ポリゴンの色を赤に
})
ちなみにマウスオーバーで色を変えると変えっぱなしになるので、マウスが上にあるときだけ色を変えたい場合にはマウスアウトで色を戻す
マウスアウトの色を指定
mapping.js
// mouseooutの時のインタラクション
.on('mouseout', function() {
this.attributes['fill'].value = base_fill_color; //元の色に戻す
}
おまけ:クリック時に色を変える
mapping.js
// clickされた時のインタラクション
.on('click', function(d) {
this.attributes['fill'].value = "blue";
});
次回は地図とグラフを連携させるというそれっぽいかんじのことをやる。