Uncaught TypeError: Unable to call the 'push' method from undefined (d3 force layout)

I can’t understand why I get this error for the life of me (using the power layout). It started when I switched to reading my nodes from a json file. If I uncomment the lines below, this will not result in an error. If I stay as it is, I get "Can't call the push method from undefined." I am not sure what the problem is. Did I miss something?

<html>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script>

   d3.json("http://katejustin.com/autosys1.json", function(data) {

   //var nodes = {};

   //data.links.forEach(function(link) {
   //   link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
   //   link.target = nodes[link.target] || (nodes[link.target] = {name: link.target}); });


var width = 200,
    height = 200;

var svg = d3.select("body").append("svg:svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    //.nodes(d3.values(nodes))
    .nodes(data.nodes)
    .links(data.links)
    .size([width, height])
    .distance(100)
    .charge(-1000)
    .start();
});
</script>
</html>
0
source share
1 answer

The problem is that you are trying to access sites by namein links. In the original implementation, you access the nodes by index.

, , , - :

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)

, , , node force.nodes.

jsFiddle: http://jsfiddle.net/chrisJamesC/nrbQ4/1/ (. , ).

+1

Source: https://habr.com/ru/post/1650978/


All Articles