JavaScript d3.js小练习中国地图
chinamap.html和china.json两个文件都放到自己的web服务上进行访问,比如nginx.
使用docker镜像搭建简单的静态nginx服务器
https://www.cnblogs.com/v5captain/p/14162506.html
http://localhost/chinamap.html
https://files.cnblogs.com/files/v5captain/china.json 右键保存该文件到本地.
chinamap.html文件内容:
<html> <head> </head> <body> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> china map:<br> <script> var w = 500*4; var h = 300*4; var color = d3.scale.category10(); //Define default path generator var path = d3.geo.path(); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); var projection = d3.geo.mercator() .center([107, 31]) .scale(850) .translate([w/2, h/2]); var path = d3.geo.path() .projection(projection); d3.json("http://localhost/china.json", function(error, root) { if (error) return console.error(error); console.log(root.features); svg.selectAll("path") .data( root.features ) .enter() .append("path") .attr("stroke","#000") .attr("stroke-width",1) .attr("fill", function(d,i){ return color[i]; }) .attr("d", path ) //使用地理路径生成器 .on("mouseover",function(d,i){ d3.select(this) .attr("fill","yellow"); }) .on("mouseout",function(d,i){ d3.select(this) .attr("fill",color(i)); }); }); </script> </body> </html>
参考:极客学院D3.js教程 https://wiki.jikexueyuan.com/project/d3wiki/chinamap.html