在d3.js全局地图中设置点

时间:2016-10-01 21:20:42

标签: javascript d3.js

我遇到的主要问题是,当我尝试在地图中绘制点时,在创建cx时,cy协调它显示为null,但如果你检查它,从我的角度来看,补丁是正确的

    d3.json(meteorites, function(meteorite){
console.log("meteorite", meteorite.features);
svg.selectAll("circle")
.data(meteorite.features)
.enter()
 .append("circle")
.attr({
cx: function(d){ return projection(d.geometry.coordinates[0], d.geometry.coordinates[1])[0];},
 cy: function(d){ return projection(d.geometry.coordinates[0], d.geometry.coordinates[1])[1];},
 r: 5,
fill: "red"

});

此外,如果您希望看到我在此处写的内容是指向我的codepen的链接http://codepen.io/DiazPedroAbel/pen/bwoBZd

我一直在尝试没有投影,但结果是相同的,null但是如果我做一个console.log()我得到了我期待的结果。可能我在这里误解了一些东西,这是我第一次在d3中绘制地图。

1 个答案:

答案 0 :(得分:4)

似乎您在JSON文件中有一些条目不包含geometry对象和附带的geometry.coordinates数组,导致脚本失败。我建议你在附加.data()时实现一个基本的过滤器,以确保你只处理定义了地理坐标的节点,而不是简单地具有以下内容:

.data(meteorite.features)

...您可以使用.filter()清除您没有geometry对象或定义的geometry.coordinates数组的对象数组中的条目:

.data(meteorite.features.filter(function(d) {
  return d.geometry && d.geometry.coordinates;
}))

请参阅corrected CodePen example,并更新以下代码块:

d3.json(meteorites, function(meteorite){
    svg.selectAll("circle")
        .data(meteorite.features.filter(function(d) {
          return d.geometry && d.geometry.coordinates;
        }))
        .enter()
        .append("circle")
        .attr({
          cx: function(d){ return projection(d.geometry.coordinates)[0];},
          cy: function(d){ return projection(d.geometry.coordinates)[1];},
          r: 5,
          fill: "red"
    });
});