Google Charts上的多个实例

时间:2015-04-28 12:09:59

标签: javascript jquery

我正在尝试获取2个谷歌图表实例,但只显示最后一个。

以下是代码:

// Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
      var jsonData = $.ajax({
          url: "charts/getData.php",
          dataType:"json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});

    }


    //Chart 2

    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
      var jsonData = $.ajax({
          url: "charts/getData.php",
          dataType:"json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data2 = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart2 = new google.visualization.PieChart(document.getElementById('chart_div2'));
      chart2.draw(data2, {width: 400, height: 240});

    }

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要致电google.load(' visual',' 1',{' packages':[' corechart']} );只有一次。我建议使用初始化函数重新组合所有drawchart()函数。见下文。除此之外你的代码看起来很好,应该工作。

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initialize);

function initialize() { 
  drawChart();
  drawChart2();
}


function drawChart() {
  var jsonData = $.ajax({
      url: "charts/getData.php",
      dataType:"json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});

}



function drawChart2() {
  var jsonData = $.ajax({
      url: "charts/getData.php",
      dataType:"json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var data2 = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart2 = new google.visualization.PieChart(document.getElementById('chart_div2'));
  chart2.draw(data2, {width: 400, height: 240});

}