日期:2014-05-16 浏览次数:20732 次
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>