3

看看我下面的 JS,我的 google 图表的 drawChart 函数。这按我的预期工作。但是,因为var chart ...在 drawChart 函数内部,动画不起作用 - 相反谷歌认为它每次都在创建一个全新的图表,并且只是刷新图表。

我想在他们的示例中执行类似操作,其中数据根据我的设置移动(1000 毫秒,默认缓动:线性)。示例在这里:https ://developers.google.com/chart/interactive/docs/animation

var chart ...如果我从drawChart函数中取出,我会收到“未定义图表”错误。感谢经常使用谷歌图表的任何人的帮助。谢谢您的帮助。

var chart = "notSet";
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(setGoogleData);
google.setOnLoadCallback(drawChart);
newValue = 0;
var data = [];
function setGoogleData(){
  data[0] = new google.visualization.DataTable(JSON_DATA_LOCATED_HERE);
  data[1] = new google.visualization.DataTable(JSON_DATA_LOCATED_HERE);
  var chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
}
function drawChart() {
  if(chart == "notSet"){
    var chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
  }
  var options = {"title":"Average Load Summary","titlePosition":"in","width":1100,"height":700,"hAxis.slantedTextAngle":90,"hAxis.position":"out","pointSize":5,"animation.duration":1000,"animation.easing":"linear","hAxis.showTextEvery":1,"hAxis.title":"Stops"};
  chart.draw(data[newValue], options);
}
function changeChart(){
  newValue = document.getElementById("chartNumber").value;
  drawChart();
}
4

1 回答 1

3

我自己从未尝试过 Google 图表,但我认为这样的代码会起作用:

var chart = null;
function drawChart() {
  if(chart === null){
     chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
  }
  var options = {"title":"Average Load Summary",
                 "titlePosition":"in",
                 "width":1100,
                 "height":700,
                 "hAxis" :{"slantedTextAngle":90,
                           "position":"out",
                           "showTextEvery":1,
                           "title":"Stops"},
                 "pointSize":5,
                 "animation":{"duration":1000,
                              "easing": 'out'};
  chart.draw(data[newValue], options);
}
function changeChart(){
  newValue = document.getElementById("chartNumber").value;
  drawChart();
}

否则,关于未定义图表的错误可能来自您可能在加载谷歌库之前放置代码的事实。因此,在 google 对象存在之前调用了图表(但很难仅用那个片段来判断)。

于 2012-04-22T18:24:35.433 回答