javascript – D3地图工具提示

我正在尝试使用D3世界地图并使用此示例构建:
http://techslides.com/demos/d3/worldmap-template.html

现在,我希望获得一个类似于国家的工具提示(即突出显示和显示名称),用于绘制到地图上的城市.

到目前为止,我已粘贴并略微更改了country-tooltip的代码,并尝试将其连接到csv的城市日期.
这是代码的后半部分,带有原始注释和我的复制粘贴:

//function to add points and text to the map (used in plotting capitals)
function addpoint(lat,lon,text) {
    var gpoint = g.append("g").attr("class", "gpoint");
    var x = projection([lat,lon])[0];
    var y = projection([lat,lon])[1];

    gpoint.append("svg:circle")
        .attr("cx", x)
        .attr("cy", y)
        .attr("class","point")
        .attr("r", 1.5);

    //conditional in case a point has no associated text
    if(text.length>0){
        gpoint.append("text")       
            .attr("x", x+2)
            .attr("y", y+2)
            .attr("class","text")       
            .text(text);
    }


gpoint

    .on("mousemove", function(d,i) {


        var mouses = d3.mouse(svg.node())
            .map( function(d) { return parseInt(d); } );

        tooltip.classed("hidden", false)
            .attr("style", "left:"+(mouses[0])+"px;top:"+(mouses[1])+"px")  
            .html(d.CapitalName);                                                       
    })


    .on("mouseout",  function(d,i) {
        tooltip.classed("hidden", true);
    }); 

当我现在将鼠标悬停在其中一个首都上时,它给了我“无法读取未定义的属性’CapitalName’.

谁能帮我?

最佳答案 正如我在评论中所说,

Have you bound any data to gpoint? It doesn’t look like it, so d3
isn’t going to pass a datum (the d in your mousemove function). Hence
the error: Cannot read property ‘CapitalName’ of undefined

这是因为您没有使用d3数据绑定.如果我正确地阅读您的代码,您正在执行以下操作:

var myDat = [{lat: 34, lon: 39, CapitalName: "akdjf"}, etc...]
for (var i = 0; i < myDat.length; i++){
   addpoint(myDat[i].lat,myDat[i].lon,myDat[i].CapitalName);
}

但是,d3,希望你的数据绑定,然后在内部循环.像这样的东西(完全未经测试,但希望你能得到这个想法):

d3.csv("data/country-capitals.csv", function(err, capitals) { 

    var gpoint = g.selectAll('.gpoint')
      .data(capitals) //<-- bind your data
      .enter() //<-- enter selection
      .append("g")
      .attr("class", "gpoint");

    gpoint.append("circle")
      .attr("cx", function(d, i){
        return projection([d.lat,d.lon])[0]; //<-- bound data and d is passed in...
      }).attr("cy", function(d, i){
        return projection([d.lat,d.lon])[1];
      });

    gpoint.on("mousemove", function(d,i) {
        var coors = d3.mouse(this);
        tooltip.classed("hidden", false)
          .attr("style", "left:"+(coors.x)+"px;top:"+(coors.y)+"px")  //<- use d3.mosue to get position
          .html(d.CapitalName);  //<-- bound data d is passed...                                                   
        });
}

编辑评论

是的,您需要转换为数字. d3为它提供了handy callback

d3.csv("data/country-capitals.csv", function(d) {
  return {
    CapitalLongitude = +d.CapitalLongitude,
    CapitalLatitude = +d.CapitalLatitude,
    CapitalName = d.CapitalName
  };
}, function(error, capitals) {
   // rest of code here
});
点赞