目录
画一个简单的地图,基于GeoJSON数据
var color = d3.scale.category20();
var projection = d3.geo.mercator()
.center([107,31])
.scale(600)
.translate([width/2,height/2]);
var path = d3.geo.path()
.projection(projection);
var groups = svg.append("g");
d3.json("china.geojson",function(error,root){
if(error)
return console.error(error);
groups.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("class","province")
.style("fill",function(d,i){
return color(i);
})
.attr("d",path)
.on("mouseover",function(d,i){
d3.select(this)
.style("fill","yellow");
})
.on("mouseout",function(d,i){
d3.select(this)
.style("fill",color(i));
});
})
基于TopoJSON数据,相邻省份的交互
d3.json("data/china.topojson",function(error,toporoot){
if(error)
return console.error(error);
var georoot = topojson.feature(toporoot,toporoot.objects.china);
var neighbors = topojson.neighbors(
toporoot.objects.china.geometries);
var groups = svg.append("g");
var paths = groups.selectAll("path")
.data(georoot.features)
.enter()
.append("path")
.attr("class","province")
.style("fill","#ccc")
.attr("d",path);
paths.each(function(d,i){
d.neighbors = d3.selectAll(
neighbors[i].map(function(j){
return paths[0][j];
})
);
})
.on("mouseover",function(d,i){
d3.select(this).style("fill","red");
d.neighbors.style("fill","steelblue");
})
.on("mouseout",function(d,i){
d3.select(this).style("#ccc");
d.neighbors.style("fill","#ccc");
});
});