D3.jsでは投影方法を指定できるので、前回使用した世界地図のデータを利用して球体にマッピングして、地球儀を表示します。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>地球をD3.jsで表示する</title> <script src="../js/d3.js"></script> <!-- D3.jsで地図データを表示するには、はじめにprojectionライブラリを 読み込ませなければなりません。このライブラリはD3.jsの後に読み込む。 --> <script src="../js/d3.geo.projection.js"></script> <style> svg{ width:640px; height:640px; border:1px solid black; background-color:#ffffff; } path{ fill:white; stroke:black; stroke-width:1; } </style> </head> <body> <h1>世界地図を表示する</h1> <svg id="map"></svg> <script src="test.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/* 世界地図を表示 */ // HTMLファイルで設定した#graphの幅、高さを取得する var svgEle = document.getElementById("map"); var svgWidth = getComputedStyle( svgEle, null) .getPropertyValue("width"); var svgHeight = getComputedStyle( svgEle, null) .getPropertyValue("height"); svgWidth = parseFloat( svgWidth ); // 整数に変換する svgHeight = parseFloat( svgHeight ); // 整数に変換する var degree = 0; // 回転角度 var earthSize = 250; // 地球のサイズ /* 地球儀のように球体をマッピングする方法としてorthographicを使う clipAngle()メソッドは何度の角度で切り抜くかを指定します。 */ var earth = d3.geo.orthographic() // 投影方法をorthographicに設定 .translate( [ svgWidth / 2 , svgHeight / 2] // 画面での表示位置調整 ) .clipAngle(90) // クリップ範囲を指定 .scale(earthSize) // スケール指定 .rotate([ degree, -25]); // 回転角度 var path = d3.geo.path().projection(earth); // パスと投影方法を指定 d3.json("../geodata/world.geojson", function(error,world){ d3.select("#map") .append("circle") // 地球は丸いので円を追加 .attr("cx", svgWidth / 2) // 表示画面の中央を中心X座標とする .attr("cy", svgHeight / 2) // 表示画面の中央を中心Y座標とする .attr("r", earthSize) // 表示する地球の半径 .style("fill","#2266ff"); // 青い地球 var earthPath = d3.select("#map") .selectAll("path") // path要素指定 .data(world.features) // データをセット .enter() .append("path") // path追加 .attr("d", path) // 地形データを設定 .style("fill",function(d,i){ // 各地域・国の色を指定 if( d.properties.name == "Antarctica"){ // 南極の場合 return "white"; } if( d.properties.name == "Japan"){ // 日本の場合 return "blue"; } return "hsl(" + i + ", 80%,60%)"; }); /* D3.jsではリアルタイムに処理を行うメソッドとして、d3.timer()があり、 パラメーターに定期的に実行する処理を書きます。今回は地球を 回転させるので、degreeの数値を変化させています。 */ d3.timer(function(){ earth.rotate([ degree, -25]); // 角度を設定 degree += 2; // 2度ずつ動かす earthPath.attr("d", path); // 地形データを設定 }); });// d3.json() |