gpt4 book ai didi

javascript - 投影 y 值时的 D3.js 问题

转载 作者:行者123 更新时间:2023-11-30 19:52:18 24 4
gpt4 key购买 nike

我正在努力从 D3 中的纬度和经度绘制一条线,特别是在投影 y 值时。

我使用以下代码和示例 json 数组绘制线条。

var json_str = [
{
"lng1": 53.587,
"lat1": -2.159,
"lng2": 53.587,
"lat2": -2.159,
},
{
"lng1": 53.587,
"lat1": -2.159,
"lng2": 53.587,
"lat2": -2.157,
}
];

d3.select("#lines").selectAll("line")
.data(json_str)
.enter()
.append("line")
.attr("x1", function (d) { return projection([d.lat1])[0]; })
.attr("y1", function (d) { return projection([d.lng1])[0]; })
.attr("x2", function (d) { return projection([d.lat2])[0]; })
.attr("y2", function (d) { return projection([d.lng2])[0]; })
.style("stroke", "black")
.style("stroke-width", 5);

当我投影 x 值时,它会得出正确的值并正确地投影到我的 map 上,但是当我投影 Y 时,使用相同的函数但在不同的字段上,它给了我疯狂的值,因此不是在我的 SVG 范围内绘图。 1299*** 附近的某处。

我使用相同的函数来投影点数据的 x 和 y 值没问题。

d3.select("#points").selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return projection([d.y, d.x])[0] })
.attr("cy", function (d) { return projection([d.y, d.x])[1] })

编辑:下面的标记答案让我很接近,但投影仍然变形。

我创建了一个 Plunker显示我的问题,其中包含下面的标记答案。本质上,“线条”SVG 向外绘制了 90 度,我无法理解为什么……

最佳答案

documentation声明(加粗我的):

projection(point)

Returns a new array [x, y] (typically in pixels) representing the projected point of the given point. The point must be specified as a two-element array [longitude, latitude] in degrees. May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection.

您在 return projection([d.lat1])[0]; 中传递了一个单一的纬度/经度值。这行不通。

我将其重构为:

var json_str = [
{
"lng1": 53.587,
"lat1": -2.159,
"lng2": 53.587,
"lat2": -2.159,
},
{
"lng1": 53.587,
"lat1": -2.159,
"lng2": 53.587,
"lat2": -2.157,
}
];

d3.select("#lines").selectAll("line")
.data(json_str)
.enter()
.append("line")
.each(function(d){
d.p1 = projection([d.lng1, d.lat1]);
d.p2 = projection([d.lng2, d.lat2]);
})
.attr("x1", function (d) { return d.p1[0]; })
.attr("y1", function (d) { return d.p1[1]; })
.attr("x2", function (d) { return d.p2[0]; })
.attr("y2", function (d) { return d.p2[1]; })
.style("stroke", "black")
.style("stroke-width", 5);

关于javascript - 投影 y 值时的 D3.js 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54352541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com