D3地图工具提示

D3 map tooltips

本文关键字:工具提示 地图 D3      更新时间:2023-09-26

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

现在,我想为地图上绘制的城市实现一个类似于国家的工具提示(即高亮显示和显示名称(。

到目前为止,我已经粘贴并稍微修改了国家/地区工具提示的代码,并试图从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);
    }); 

当我现在将鼠标悬停在其中一个大写字母上时,它会显示undefined的"Cannot read property"CapitalName"。

有人能帮我吗?

正如我在评论中所说,

你把数据绑定到gpoint了吗?它看起来不像,所以d3不会传递数据(mousemove函数中的d(。因此错误:无法读取未定义的属性"CapitalName">

这是因为您没有使用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为它提供了一个方便的回调:

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
});