我是 d3.js 的新手,正在尝试一些简单的事情。我已经绘制了一个读取 file1 和 file2 的世界地图。 file2 按 indexID、lat 和 lon 列出机场。 file1 通过 indexID 对机场进行配对。我想画一条弧线、直线或任何东西来连接它们。这个想法是产生这样的东西:http://mbostock.github.io/d3/talk/20111116/airports.html使用不同的数据集
但是这个例子太难理解了。
下面的代码正确地绘制了机场的 map 并绘制了圆圈,但如何连接它们还有待观察。
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script type="text/javascript" src="d3/d3.v3.js"></script>
<script src="js/topojson.v0.min.js"></script>
<script>
var width = 2000, height = 2000;
var projection = d3.geo.mercator().center([0, 5]).scale(100).rotate([0, 0]);
var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
var path = d3.geo.path().projection(projection);
var g = svg.append("g");
d3.json("json/world-110m2.json", function(error, topology) {// load and display the World
g.selectAll("path").data(topojson.object(topology, topology.objects.countries).geometries).enter().append("path").attr("d", path)
});
d3.csv("file1", function(flights) { //Attempt to draw arcs
var linksByOrigin = {}, countByAirport = {}, locationByAirport = {}, positions = [];
var arc = d3.geo.greatArc().source(function(d) {
return locationByAirport[d.source];
}).target(function(d) {
return locationByAirport[d.target];
});
flights.forEach(function(flight) {
var origin = flight.origin, destination = flight.destination, links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
links.push({
source : origin,
target : destination
});
countByAirport[origin] = (countByAirport[origin] || 0) + 1;
countByAirport[destination] = (countByAirport[destination] || 0) + 1;
});
d3.csv("file2", function(error, data) {// read in and plot the circles
g.selectAll(".blue.circle").data(data).enter().append("circle").attr("class", "blue circle").attr("cx", function(d) {
return projection([d.lon, d.lat])[0];
}).attr("cy", function(d) {
return projection([d.lon, d.lat])[1];
});
g.selectAll("path.arc").data(function(d) {
return linksByOrigin[data.ctuid] || [];
}).enter().append("svg:path").attr("class", "arc").attr("d", function(d) {
return path(arc(d));
});
});
});
</script>
</body>
</html>
我是新手,所以代码可能很草率,但任何关于从 CSV 中提取的连接点的提示都将不胜感激。谢谢!
最佳答案
要在点之间绘制弧线,为什么不使用带有弧指令(A)的路径。我也尝试过greatArc,但没有用。但从 this discussion 中找到了一个替代品替代方案如下:
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr +
" 0 0,1 " + d.target.x + "," + d.target.y;
});
替换
path(arc(d))
使用上面的代码段并根据您的值替换 x 和 y 值。这对我来说就像魅力一样。希望这可以帮助。
关于d3.js:从文件中绘制 map 上两点之间的弧线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156283/