利用d3.js繪製中國地圖

d3.js是一個比較強的資料視覺化js工具。利用它畫了一幅中國地圖,如下圖所示:

原始碼如下:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="d3.js"></script>
<script type="text/javascript" src="d3.csv.js"></script>
<script type="text/javascript" src="d3.geo.js"></script>
<script type="text/javascript" src="d3.geom.js"></script>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
var w = 1280,
h = 800;
var projection = d3.geo.azimuthal()//  //mercator()
//.mode("equidistant")
//.origin([-98, 38])
//.scale(1400)
//.translate([640, 360]);
.mode("equidistant")
.origin([107, 32])///???
.scale(1000)
.translate([w/2, h/2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#map").insert("svg:svg")
//.append('svg')//
.attr("width", w)
.attr("height", h);
var states = svg.append("svg:g")
.attr("id", "states");
var circles = svg.append("svg:g")
.attr("id", "circles");
var texts = svg.append("svg:g")
.attr("id", "texts");
var cells = svg.append("svg:g")
.attr("id", "cells");
d3.json("china.json", function(collection) {
states.selectAll("path")
.data(collection.features)
.enter().append("svg:path")
.attr("d", path)
.attr('fill','#ddd')
.attr('stroke','#222')
.attr('stroke-width','1px')
;
});
var positions=[];
d3.csv('china-cities.csv',function(c){
circles.selectAll("circle")
.data(c)
.enter().append("svg:circle")
.attr("cx", function(d,i){return projection([d.lon,d.lat])[0];})
.attr("cy",function(d,i){return projection([d.lon,d.lat])[1];})
.attr("r", 3)
.attr('fill','red');
texts.selectAll("text")
.data(c)
.enter().append("svg:text")
.text(function(d){return d.city;})
.attr("x", function(d){
var local=projection([d.lon,d.lat]);
if(d.lon=='113.5575191')//處理澳門
return (local[0]-30);
else return local[0];})
.attr("y",function(d){
var local=projection([d.lon,d.lat]);
if(d.lat=='39.1439299') return (local[1] 10);//處理天津
else return local[1];
})
.attr('fill','#000')
.attr('font-size','14px')
;
});
</script>
</body>
</html>

china-cities.csv中國城市經緯度csv檔案  http://download.csdn.net/detail/svap1/7868247

中國地圖json格式   http://download.csdn.net/detail/svap1/7821315