我正在试验 D3 世界地图并使用此示例构建:http://techslides.com/demos/d3/worldmap-template.html
现在我想为绘制在 map 上的城市实现一个类似于国家(即突出显示和显示名称)的工具提示。
到目前为止,我已经粘贴并稍微更改了国家/地区工具提示的代码,并尝试将其连接到 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
数据绑定(bind)。如果我没看错你的代码,你就是在做这样的事情:
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
但是,希望您的数据绑定(bind),然后在内部循环。像这样的东西(完全未经测试,但希望你能明白):
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
});
关于javascript - D3 map 工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31209213/