'd3: updating a force directed layout from an API call

Please bear with me: i'm new!

I'm trying to update a d3 force layout through data coming from a custom API call (the link is included if you want to explore: it's for a museum exhibit which shows in the gallery the expressions of the public about the artworks on show. There's only a few text data there as of now).

But strange things happen, i have guessed it's due to javscript object instances not "linking"/"referencing" each others, do when viz-time come the get lost.

UPDATE!: auto-solved!

Here's the code:

var urlapi_viz = "https://herserver.avnode.net/WWWServer/api.php";
var chart;

function setup_Chart(){
        chart = new Object();
        chart.maxnode = 1;
        chart.nodesscale;
        chart.textsscale;
        chart.linksscale;
        chart.svg = null;
        chart.simulation = null;
        chart.g = null;
        chart.link = null;
        chart.node = null;
        chart.labels = null;
        chart.wwidth;
        chart.hheight;
        chart.clickednode = "";
        chart.nodesscale = d3.scaleLinear().domain([0,chart.maxnode]).range([8,50]);
        chart.textsscale = d3.scaleLinear().domain([0,chart.maxnode]).range([8,40]);
        chart.linksscale = d3.scaleLinear().domain([0,chart.maxnode]).range([0.2,3]);
}


drawGRAPH();
setInterval(updategraph, 5000);

function drawGRAPH(){
    chart.wwidth = $("#viz1").width();
    chart.hheight = $("#viz1").height();


        chart.svg = d3.select("#viz1").append("svg")
        .style("width", $("#viz1").width() + 'px')
        .style("height", $("#viz1").height() + 'px');


        chart.g = chart.svg.append("g");
        chart.link = chart.g.append("g").selectAll(".link");
        chart.node = chart.g.append("g").selectAll(".node");
        chart.labels = chart.g.append("g").selectAll(".label"); 


      var zoom_handler = d3.zoom()
            .on("zoom", zoom_actions);

        zoom_handler(chart.svg);


        // la sumulazione del network
        chart.simulation = d3.forceSimulation()
            .force("charge", d3.forceManyBody().strength(-160))
            .force("link", d3.forceLink().id(function(d) { return d.id; }).distance(60))
            .force("collide",d3.forceCollide( function(d){return d.r + 8 }).iterations(16) )
            .force("x", d3.forceX())
            .force("y", d3.forceY())
            .alphaTarget(1)
            .on("tick", ticked); // ticked --> la funzione che viene chiamata a ogni frame
}

function updategraph(){
        $.post(
            urlapi_viz,
            {
                "cmd": "GETDATAFORVIZ",
                "iw": 1,
                "e": 1,
                "v": Math.random()
            },
            function(data,textStatus){

                // la struttura dati della visualizzazione
                // - la struttura del netword con gli array di nodi e link
                //      - i nodi hanno id che inizia con "o" nel caso delle opere
                //      -                                "r" nel caso delle risposte e i dati (sia quelle del MAXXI che quelle del pubblico)
                // - le questions_viz
                //console.log(data);

                graph_viz = data.graph;
                questions_viz = data.questions;

                console.log(graph_viz.links);

                chart.node = chart.node.data(graph_viz.nodes, function(d) { return d.id;});
                chart.node.exit().remove();
                chart.node = chart.node.enter().append("rect")
              .attr("class",function(d){
                var c = "node";
                if(d.id.startsWith("o")){
                    c = c + " opera";
                } else if(d.id.startsWith("r")){
                    if(ismaxxiquestion(d.domanda)){
                        c = c + " maxxianswer"; 
                    } else {
                        c = c + " answer";  
                    }
                    
                }
                return c;

              })
              .attr("id",function(d){
                return d.id;
              })
              .attr("width",function(d){
                var s = 20;
                if(d.id.startsWith("o")){
                    s = sizes_viz.opera;
                } else if(d.id.startsWith("r")){
                    if(ismaxxiquestion(d.domanda)){
                        s = sizes_viz.maxxianswer;  
                    } else {
                        s = sizes_viz.answer;
                    }
                } else {
                    s = sizes_viz.default;
                }
                return s;
              })
              .attr("height",function(d){
                var s = 20;
                if(d.id.startsWith("o")){
                    s = sizes_viz.opera;
                } else if(d.id.startsWith("r")){
                    if(ismaxxiquestion(d.domanda)){
                        s = sizes_viz.maxxianswer;  
                    } else {
                        s = sizes_viz.answer;
                    }
                } else {
                    s = sizes_viz.default;
                }
                return s;
              })
              .on("click",function(e,d){
                managePopup(e,d);
              })
            .call(d3.drag()
                    .on("start", dragstarted)
                    .on("drag", dragged)
                    .on("end", dragended))
            .merge(chart.node); 

                chart.link = chart.link.data(graph_viz.links, function(d) { return d.id; });
                chart.link = chart.link.enter().append("line").call(function(link) { 
                    link.attr("class","link");
                link.attr("id",function(d){
                    return d.source.id  + "-" + d.target.id;
                });
                link.transition().attr("stroke-width", function(d){ 
                    var ww = +(d.c) ;
                    return 1; 
                } ); 
              })
              .merge(chart.link);
                chart.link.exit().remove();

                chart.simulation.nodes(graph_viz.nodes);
                chart.simulation.force("link").links(graph_viz.links);
                chart.simulation.alpha(0.3).restart();

            }
        );
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source