Google 动态绘制多个图表时图表不显示

Google Chart doesn't display when drawing multiple charts dynamically

我收到一些带有 ajax 的数据,我想将其显示为 google 折线图。我不知道我要显示多少图表,所以我使用 javascript forEach 调用我的函数 drawchart();

使其动态化

我在这里收到数据:

$j.ajax({
        type: "GET",
        url: "../"+folder_destination+"slimrest/getValues",
        data: "",
        success: function(msg){
            msg.forEach(function(entry) {
                drawchart(entry['id'], entry['data']);
            });
        }
}); 

这是我的函数,它应该添加一个具有唯一 ID 的 div,然后在里面绘制图表:

function drawchart(id_rec){

    $j("#charts_cartes").append("<div id=\"gchart_"+id_rec+"\"></div>");

    var data = new google.visualization.DataTable();
    data.addColumn('number', 'max');
    data.addColumn('number', 'min');
    data.addColumn('number', 'Mesures');

    //Will be dynamic as soon as I'll be able to print more than one chart
    data.addRows([
      [1,  37.8, 80.8],
      [2,  30.9, 69.5]
    ]);

    var options = {
      width: 500,
      height: 200
    };

    var chart = new google.charts.Line(document.getElementById('gchart_'+id_rec));
    chart.draw(data, options);
}

我在 html 代码中看到了我的 divs,但第二个图表从未显示过。

其中一个图表的 <svg></svg> 应答器似乎是空的 :

<div id="charts_cartes">
    <div id="gchart_39">
        <div style="position: relative; width: 500px; height: 200px;">
            <div
                style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;">
                <svg width="500" height="200">
                    <defs><!-- [chart code well displayed but too long to write here] --></defs>
                </svg>
            </div>
        </div>
    </div>
    <div id="gchart_40">
        <div style="position: relative; width: 500px; height: 200px;">
            <div
                style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;">
                <svg width="500" height="200">
                <defs></defs></svg>
            </div>
        </div>
    </div>
</div>

修复了向 googlechart 的绘图函数添加 setTimeout 的问题:

setTimeout(function(){ chart.draw(data, options); }, 1000);

如果几乎同时绘制多个图表,肯定存在一些冲突...

上面的解决方案有效,但仅 1 毫秒的 setTimeout 有效,因此如果您使用某些显示逻辑动态生成图表,它不会在 1000 毫秒内加载。

所以这在 AngularJS 应用程序中也对我有用。

setTimeout(function(){ chart.draw(data, options); }, 1);