1. 程式人生 > >D3.js中載入地圖GeoJson

D3.js中載入地圖GeoJson

D3.js函式庫可用來實現資料的圖形化顯示,功能強大,特別是配合GeoJSON地圖,只需要幾條指令就可以載入並顯示地圖,實現資料的地圖顯示。載入GeoJSON地圖的方法為:

var width = 900,height = 600;
var svg = d3.select("#chart").append("svg").attr("width", width).attr("height", height);
var projection = d3.geo.mercator()//設定投影函式 
  .center([108.0, 37.5])// 函式是用於設定地圖的中心位置,[107,31] 指的是經度和緯度。
  .scale(700)//函式用於設定放大的比例。
  .translate([width/2, height/2]);//函式用於設定平移。
var path = d3.geo.path().projection(projection);
var color = d3.scale.category20();
d3.json("china.json", function(error, json) {
  if (error)
    return console.error(error);
  console.log(json.features);
  var china= svg.selectAll("path")
    .data( json.features )
    .enter()
    .append("path")
    .attr("stroke","#000")//線的顏色
    .attr("stroke-width",1)
    .attr("fill", function(d,i){
      return color(i);
    })
    .attr("d", path )
    .attr("fill",color(i));
  })
  .append("text").attr("transform",function(d,a){
    return d.name;
  });

其中china.json是中國的GeoJSON格式地圖,可以在網上下載到。注意,上述方法是使用d3.v3版本,v4版本有了比較大的變化,與v3方法的名稱大部分完全不同。