访问Google Charts draw()函数中的数据属性

时间:2017-05-10 21:06:58

标签: javascript google-chrome charts google-visualization

我正在尝试访问drawVisualization()函数之外的数据变量和addRow()。 我一直遇到的问题是如果我在draw函数之外有data / addRow我在控制台中有错误“无法读取未定义的属性'DataTable'或者它的”无法读取未定义的属性'数据' 不确定这对谷歌API是否可行。但请分享你的想法。检查下面的代码

var data;
var chart;

function drawVisualization() {

    data = new google.visualization.DataTable();
    data.addColumn('string', 'data');
    data.addColumn('number', 'date');

    data.addRow([timeArr[i], valueArr[i]]);


    //console.log(valueArr);
    // use a DataView to 0-out all the values in the data set for the initial draw
    var view = new google.visualization.DataView(data);


    // Create and draw the plot
    chart = new google.visualization.LineChart(document.getElementById('visualization'));


    var options = {
        title:" ",
        width: 960,
        height: 460,
        bar: { groupWidth: "40%" },
        legend: { position: "bottom" },
        animation: {"startup": true},
        curveType: 'function',
        lineWidth: 3,
        backgroundColor: '#f9f9f9',
        colors: ['red'],
        tooltip: {
            textStyle: {
              color: 'red',
              italic: true
            },
            showColorCode: true
        },
        animation: {
            startup: true,
            easing: 'inAndOut',
            //duration: 500
        },
        vAxis: {
            title: '',
            gridlines: {
              count: 8,
              color: '#999'
            }
            /*minValue: 1.3,
            maxValue: 1.4*/
        },
        hAxis: {
          title: 'Time Stamp'
        },
    };


    chart.draw(view, options);

}

1 个答案:

答案 0 :(得分:0)

1)data之外的某处定义drawVisualization

var data;

function drawVisualization() {
  ...

2)var内的data移除drawVisualization

var data;

function drawVisualization() {
  data = new google.visualization.DataTable();  // <-- remove var declaration
  data.addColumn('string', 'data');
  data.addColumn('number', 'date');

3),请确保在data callback被解雇之后才使用google.charts.load ...

编辑

您可以在drawVisualization之外定义图表

第一次调用drawVisualization时,
你可以访问任何变量上的任何方法......

var data;
var chart;

function drawVisualization() {
  data = new google.visualization.DataTable();  // <-- remove var declaration
  data.addColumn('string', 'data');
  data.addColumn('number', 'date');

  chart = new google.visualization.LineChart(document.getElementById('visualization'));