<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>可拖动的地图</title> </head> <style> .link { stroke: #ccc; stroke-width: 1; } </style> <body> <script src = "d3.js"></script> <script src = "js/movemap.js"></script> </body> </html>
一、常规设置:
var width = 1000, height = 1000; var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height) .append("g") .attr("transform","translate(0,0)") var color = d3.scale.category20()二、定义投影函数:
var projection = d3.geo.mercator() .center([107,31]) //地图中心,这里表示的经度、纬度 .scale(850) //放大尺寸 .translate([width/2,height/2]); //设定平移三、定义path路径函数:
var path = d3.geo.path() .projection(projection);四、读取数据并绘图:
d3.json("china_simple.json",function(error,root){ if(error) return console.log(error); console.log(root.features); //数据转换 //定义变量 nodes 和 links var nodes = []; var links = []; //对于取到的每一个数据,都要进行无名函数中的操作 root.features.forEach(function (d,i){ var centroidArray = path.centroid(d);//计算各省的中点 var centroid = {}; centroid.x = centroidArray[0];//保存各省中点的x centroid.y = centroidArray[1];//保存各省中点的y centroid.feature = d;//将其他相关信息赋给centroid.feature nodes.push(centroid); //将所有信息插入到nodes里面 }); //d3.geom.voronoi : 用默认的访问器创建一个泰森多边形布局。 //voronoi.triangles : 计算Delaunay mesh为一个三角形密铺。 var triangles = d3.geom.voronoi().triangles(nodes);//对nodes中的定点进行三角剖分,用三角形链接各顶点,返回的数组是: //将三角形的三边存到links中 triangles.forEach(function(d,i){ links.push(edge(d[0],d[1])); links.push(edge(d[1],d[2])); links.push(edge(d[2],d[0])); }); //定义力学图force函数并设定force的各个参数 var force = d3.layout.force() .size([width,height]) .gravity(0) .charge(0) .nodes(nodes) .links(links) .linkDistance(function (d) {return d.dist ance;}) .start(); //画点 var node = svg.selectAll("g") .data(nodes) .enter() .append("g") .attr("transform",function(d){return "translate("+-d.x+","+-d.y+")"}) .call(force.drag) .append("path") .attr("transform", function (d) { return "translate("+ d.x+","+ d.y+")" }) .attr("stroke","#000") .attr("stroke-width",1) .attr("fill",function(d,i){return color(i)}) .attr("d", function (d) { return path(d.feature) }); //画线 var link = svg.selectAll("line") .data(links) .enter() .append("line") .attr("class","link") .attr("x1",function(d){return d.source.x}) .attr("y1",function(d){return d.source.y}) .attr("x2",function(d){return d.target.x}) .attr("y2",function(d){return d.target.y}); //运动刷新 force.on("tick",function(){ link.attr("x1",function(d){return d.source.x}) .attr("y1", function (d) {return d.source.y}) .attr("x2",function(d){return d.target.x}) .attr("y2", function (d) {return d.target.y}) node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); }); }); function edge(a, b) { var dx = a[0] - b[0], dy = a[1] - b[1]; return { source: a, target: b, distance: Math.sqrt(dx * dx + dy * dy) }; }