d3.js:为什么是d3.geo.path()给NaN? [英] d3.js: why is d3.geo.path() giving NaN?
问题描述
我试图做一些在线映射与d3,但遇到一个问题,当我尝试绘制两点之间的线。
I am trying to do some online mapping with d3, but running into a problem when I try to plot a line between two points.
我计算了两个多边形(源和目标)的质心
I have calculated the centroid of two polygons (source and target)
在代码中:
var projection = d3.geo.mercator()
.scale(width)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
从JS控制台:
> path({type: "LineString",
coordinates: [path.centroid(source_country), path.centroid(target_country)]});
"M277.05056877663407,121.67976219138909L-694.1792414247936,NaN"
,质心计算似乎工作正常(绘制这些点在地图上显示它们)
Yet, the centroid calculations seem to be working fine (plotting those points shows them on the map)
> [path.centroid(source_country), path.centroid(target_country)]
[
Array[2]
0: 103.89396329123777
1: -41.453727169465765
length: 2
__proto__: Array[0]
,
Array[2]
0: -260.3172155342976
1: -245.57309459883245
length: 2
__proto__: Array[0]
任何想法为什么NaN出现在
Any ideas why that NaN is appearing at the end of the path generated for my LineString?
推荐答案
这里的问题是你投射lat / lon坐标两次。 path()
运算符期望将lat / lon和project投影到像素; path.centroid()
方法也期望一个纬度/经度几何,并且还产生一个基于像素的投影。
The problem here is that you're projecting the lat/lon coordinates twice. The path()
operator expects to take lat/lon and project to pixels; the path.centroid()
method also expects a lat/lon geometry, and also produces a pixel-based projection.
所以当你在 [path.centroid(...))上调用
,您试图投影已投影的坐标。你得到 path
path.centroid(...)] NaN
,因为像素坐标的y位置-245超出了经度值的范围。
So when you call path
on [path.centroid(...), path.centroid(...)]
, you're trying to project already-projected coordinates. You get at NaN
because the y-position of the pixel coordinates, -245, is out of bounds for a longitude value.
修复此问题的最简单方法是使用 d3.svg.line
创建质心中心路径。我没有测试这个,但我认为它会像:
The easiest way to fix this is probably to use d3.svg.line
to create the centroid-centroid path. I haven't tested this, but I think it would look like:
var line = d3.svg.line();
line([path.centroid(source_country), path.centroid(target_country)]);
这篇关于d3.js:为什么是d3.geo.path()给NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!