【问题标题】:how to work with dynamic data and google charts?如何使用动态数据和谷歌图表?
【发布时间】:2012-04-02 06:43:56
【问题描述】:

例如,我们在Google Code API 有这个折线图

此图表反映了一组已定义的数据,但是我想使用我自己的来自 php/mysql 脚本的数据来创建图表。

这是google提供的嵌入html页面的代码..

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['imagelinechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        // Create and populate the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.addRows(3);
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);

        // Create and draw the visualization.
        new google.visualization.ImageLineChart(document.getElementById('visualization')).
            draw(data, null);  
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 300px; height: 300px;"></div>
  </body>
</html>

我想到的选择是将以下代码保持在循环中并生成数据。有人有什么简单有效的方法来做到这一点吗?

data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.addRows(3);
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);

【问题讨论】:

    标签: php mysql dynamic-data google-visualization


    【解决方案1】:

    您的问题涉及到让我非常沮丧的事情:Google 的 API 文档不是很好!特别是对于 Charts API,基本上在他们的所有示例中,他们的图表数据都是硬编码在页面中的,并且在现实生活中,您基本上总是会渲染存储在数据库中并传输到浏览器的数据。

    1) 您需要在服务器上使用一些代码(我使用 PHP)来查询数据库、“打印”并传输 JSON/复杂数据结构,这是一个对象,其中属性是包含具有属性和值的附加对象的数组以 Google 的 Chart JavaScript 期望在浏览器中接收它的确切格式。我是这样做的:

    $sql = "SELECT year,d_pop FROM metrics WHERE year IN ('1940','1950','1960','1970','1980')";
    
    $sth = mysql_query($sql, $conn) or die(mysql_error());
    
    //start the json data in the format Google Chart js/API expects to recieve it
    $JSONdata = "{
               \"cols\": [
                   {\"label\":\"Year\",\"type\":\"string\"},
                   {\"label\":\"Detroit Population\",\"type\":\"number\"}
                 ],
            \"rows\": [";
    
    //loop through the db query result set and put into the chart cell values
    while($r = mysql_fetch_assoc($sth)) {
       $JSONdata .= "{\"c\":[{\"v\": " . $r['year'] . "}, {\"v\": " . $r['d_pop']  ."}]},";
    
    }    
    
    //end the json data/object literal with the correct syntax
    $JSONdata .= "]}";
    
    echo $JSONdata;
    

    2) 您需要在页面上的 JavaScript 中接收该 JSON 对象并将其传递给 Google 的 Chart JS。我引入了 JQuery,然后像这样使用它的 AJAX 方法:

    function drawChart() {
        var jsonData = $.ajax({
            url: "index_db.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.LineChart(document.getElementById('chart_div'));
        chart.draw(data, {vAxis: {minValue: 0}});
    }
    

    我的代码 sn-ps 专注于查询 mySQL DB、生成 Google Charts API 需要的 JSON 对象以及使用 JQuery 和 AJAX 接收它的关键部分。希望这能照亮!

    【讨论】:

    • 很好的答案@Andrew Koper,这是一个很好的方法......不幸的是,jquery 的最新方法已弃用async: false,所以如果你愿意,请确保使用 1.6.2 到 1.7.2走这条路。
    【解决方案2】:

    您可以将数据作为json 传递,而不是循环并使用data.setCell() 传递

    在 php 端制作你的数据 json 格式。使用json_encode()。而在 Api 上使用这种方法来传递数据。查看此链接了解更多信息

    http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_toJSON

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多