文章标题
在学一张图的时候要弄清作者的写作思路,哪几个元素是成套出现的,谁在前谁在后,将思路轨迹理清楚,就像这篇文章
1.projection—>path(projection)—->svg添加path并绑定数据,生成地图
2.marker中添加arrow的path,生成箭头—–》marker中添加circle,定义起点—->svg中添加line标签,并绑定circle与arrow
marker的数据形式,帮助我们理解为什么要这样做
var width=500,height=500;
/*生成svg画布*/
var svg=d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height)
/*给地理路径生成器定义投影方式*/
var projection=d3.geo.mercator()
.center([107,31])
.scale(600)
.translate([width/2,height/2]);
var path=d3.geo.path().projection(projection);
下边是定义marker,marker标签包裹path或者circle
var defs=svg.append("defs");
/*定义arrowmarker*/
var arrowMarker=defs.append("marker")
.attr("id","arrow")
.attr("markerUnits","strokeWidth")
.attr("markerWidth","10")
.attr("markerHeight","10")
.attr("viewBox","0 0 12 12")
.attr("refX","6")
.attr("refY","6")
.attr("orient","auto");
var arrow_path = "M2,2 L10,6 L2,10 L6,6 L2,2";
arrowMarker.append("path")
.attr("d",arrow_path)
.attr("fill","red");
var startMarker=defs.append("marker")
.attr("id","startPoint")
.attr("markerUnits","strokeWidth")
.attr("markerWidth","12")
.attr("markerHeight","12")
.attr("viewBox","0 0 12 12")
.attr("refX","6")
.attr("refY","6")
.attr("orient","auto");
startMarker.append("circle")
.attr("cx",6)
.attr("cy",6)
.attr("r",2)
.style("fill","red");
最后加载数据
d3.json("china.topojson",function(error,toporoot){
/*topojson转换为geojson*/
if(error){
window.alert("loading data error");
}
var georoot=topojson.feature(toporoot,toporoot.objects.china);
console.log(georoot)
var province=svg.append("g")
province.selectAll("path")
.data(georoot.features)
.enter()
.append("path")
.attr("class","province")
.style("fill","steelblue")
.attr("d",path)
var beijing = projection([116.3, 39.9]);
var guilin = projection([110.3, 25.3]);
svg.append("line")
.attr("class","line_to")
.attr("x1",guilin[0])
.attr("y1",guilin[1])
.attr("x2",beijing[0])
.attr("y2",beijing[1])
.attr("marker-start","url(#startPoint)")
.attr("marker-end","url(#arrow)");
})