ウィリアムのいたずらの、まちあるき、たべあるき

ウィリアムのいたずらが、街歩き、食べ物、音楽等の個人的見解を主に書くブログです(たま~にコンピューター関係も)

D3.jsで日本地図出して、点をうつ方法

2014-09-16 17:18:47 | JavaとWeb
前に、Rで日本地図出して、気象庁のデータ読み込んで、軌跡を描くところまでは、できた>で、最後に「D3.jsで日本地図出して、点をうつ」ところまで出来たと書いておきながら、その方法を書いていなかった。

今回、その方法を書いておく。

【お題】
結局、こんなやつを出す。


【前提】

日本地図を用意する。本当は

http://cloud.aitc.jp/20140627_D3js/201406xx_D3js.pdf

の15ページや

http://www.slideshare.net/dsuket/d3js-35239244

の34シート目にあるように、
(1)http://www.naturalearthdata.com
   にいって、データをshape形式でとってきて
(2)それをGeoJSONに変えるため、ogr2ogrし
(3)さらにGeoJSONをTopoJSON形式に変換

となるんだけど、今回は、そのシートの40枚目にある
http://bit.ly/japantopo
つまり、
https://dl.dropboxusercontent.com/u/1662536/topojson/japan.topojson
のデータを使います。


【プログラム】
こんなかんじ
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Sample 01</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script type="text/javascript">

$(function(){

//	日本地図
var topoJsonUrl = "https://dl.dropboxusercontent.com/u/1662536/topojson/japan.topo.json";

//	変数設定
var width = 500,
    height = 500,
    scale = 1;

// bodyにSVGをつくり、g(地図グループ)を作る
d3.select("body").append("svg")
	.attr("width", width)
	.attr("height", height)
	.append("g").attr("id", "all-g");

//投影法の設定
var projection = d3.geo.mercator()
		.center([138, 38])
		.scale(1200)
		.translate([width / 2, height / 2]);
    
// 地図読み込み
d3.json(topoJsonUrl, onLoadMap);

// データ設定
var mydata =[
[135.25508,34.336263],
[140.103417,39.706976],
[139.69194,35.659432]
];

//==============================//
//	地図と点を描く		//
//==============================//
function onLoadMap (error, jpn) {

	//地図を描く
	var path = d3.geo.path().projection(projection);
	var features = topojson.object(jpn, jpn.objects.japan);
	d3.select("#all-g")
        	.append("g").attr("id", "path-g").selectAll("path")
            	.data(features.geometries)
            	.enter()
            	.append("path")
            	.attr("fill", "#f0f0f0")
            	.attr("stroke", "#999")
            	.attr("stroke-width", 0.5/scale)
            	.attr("d", path);

	//	点を描く
	d3.select("#all-g")
		.append("g").attr("id","circle-g").selectAll("circle")
		.data(mydata)
		.enter()
		.append("circle");

	//	赤く塗る
	d3.selectAll("#circle-g circle")
		.attr("fill", "red")
		.attr("opacity", 0.5)
		.attr("transform", function(d) { 
			var coord = projection([d[0], d[1]]);
			return "translate(" + coord.join(",") + ")"; 
		})
		.attr("r", 5/scale);
}

});

</script>
</head>
<body>

</body>
</html>


【参考】
上記スライドシートのほか
http://jsfiddle.net/dsuket/sEFjd/
など。
この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« SPSS Modelerだと、たしかに... | トップ | JQueryで、セレクタをID指定(... »
最新の画像もっと見る

JavaとWeb」カテゴリの最新記事