我正在尝试使用基于纬度和经度的 D3 地理库在 map 上绘制几个点。但是,当我将这些值传递到我的投影函数时,它会导致坐标超出我的 SVG 图像的范围。我的代码基于 this example provided in the documentation .
我已将当前代码放在:http://bl.ocks.org/rpowelll/8312317
我的源数据是一个简单的对象数组,格式如下
var places = [
{
name: "Wollongong, Australia",
location: {
latitude: -34.42507,
longitude: 150.89315
}
},
{
name: "Newcastle, Australia",
location: {
latitude: -32.92669,
longitude: 151.77892
}
}
]
在此之后,我设置了一个 Plate Carrée 投影,如下所示:
var width = 960,
height = 480
var projection = d3.geo.equirectangular()
.scale(153)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection)
从那里我使用与链接示例有效相同的代码绘制 map 。在脚本的最后,我使用以下代码在此 map 上绘制点:
svg.selectAll(".pin")
.data(places)
.enter().append("circle", ".pin")
.attr("r", 5)
.attr("transform", function(d) {
return "translate(" + projection([
d.location.latitude,
d.location.longitude
]) + ")"
})
但是,此代码会导致点超出 SVG 元素的边界。有什么明显的我做错了吗?
最佳答案
您的代码中有一个简单的错字——坐标应作为(经度、纬度)传递给投影,而不是相反。这段代码应该可以正常工作:
svg.selectAll(".pin")
.data(places)
.enter().append("circle", ".pin")
.attr("r", 5)
.attr("transform", function(d) {
return "translate(" + projection([
d.location.longitude,
d.location.latitude
]) + ")";
});
关于javascript - 使用 D3 在 map 上绘制点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20987535/