世界地図を表示したので、今回は日本国内の地図を表示します。サンプルコードにコメントを付しましたので、そちらをご覧ください。
地図データは
手順:
1.上記のリンクより表示したい都道府県の数値情報をダウンロードする。
2.QGISソフトなどでダウンロードした.shp→.geojsonファイルへ変換する。
その際、ダウンロードした.shpファイルはSHIFT-JSになっているので、geojsonファイルへ
保存するときはUTF-8へ変換することを忘れないでください。
サンプルコードの実行結果はこちら
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 |
/* 世界地図を表示 */ // 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 path = d3.geo.path() .projection( d3.geo.mercator() .center([139.189, 35.3697]) .scale(40000) .translate([200,320]) ); // パスと投影方法を指定 d3.json("../geodata/kanagawa.geojson", function(error,pref){ d3.select("#map") .selectAll("path") .data(pref.features) .enter() .append("path") // パスを追加 .attr("d", path) // 地形データを設定 .style("fill",function(d,i){ /* 国土数値情報の行政区域データでは、市町村名は propertiesオブジェクトのN03_004プロパティに 格納されています。N03_004プロパティの文字列を末尾から 検索して、市町村を判定する。 */ if( d.properties.N03_004.lastIndexOf("市") > -1 ){ // 市なら空色 return "skyblue"; } if( d.properties.N03_004.lastIndexOf("村") > -1 ){ // 村なら黄色 return "yellow"; } if( d.properties.N03_004.lastIndexOf("町") > -1 ){ // 町ならピンク return "pink"; } return "gray"; }); });// d3.json() |