Uncaught TypeError: Cannot call method 'push' of undefined (d3 force layout)

你。 提交于 2019-11-29 12:45:35

The problem is that you try to access the nodes by name in links. In the original implementation you access the nodes by index.

Here is a trick that I usually use in these situations, even if I am sure that something easier exists:

var findNode = function(id) {
    for (var i in force.nodes()) {
        if (force.nodes()[i]["name"] == id) return force.nodes()[i]
    };
    return null;
}

var pushLink = function (link) {
    //console.log(link)
    if(findNode(link.source)!= null && findNode(link.target)!= null) {        
        force.links().push ({
            "source":findNode(link.source),
            "target":findNode(link.target)
        })
    }
}

var force = d3.layout.force()
    .nodes(data.nodes)
    .size([width, height])
    .distance(100)
    .charge(-1000)
    .start();

data.links.forEach(pushLink)

So, the goal of these functions is to replace for each link, its source and its destination by the actual object representing the node in force.nodes.

You can find a working jsFiddle here: http://jsfiddle.net/chrisJamesC/nrbQ4/1/ (See via the console as nothing is displayed in the visualization).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!