如何使用动态数据和谷歌图表?

Dja*_*ous 4 php mysql dynamic-data google-visualization

例如,我们在Google Code API上有此折线图

这个图表反映了一组定义的数据,但是我想用php/mysql脚本中自己的数据创建图表.

这是谷歌提供的嵌入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>
Run Code Online (Sandbox Code Playgroud)

我想到的选项是将以下代码保存在循环中并生成数据.有人有一些简单有效的方法吗?

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);
Run Code Online (Sandbox Code Playgroud)

And*_*per 10

你的问题涉及到让我很沮丧的事情:谷歌的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;
Run Code Online (Sandbox Code Playgroud)

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}});
}
Run Code Online (Sandbox Code Playgroud)

我的代码片段专注于查询mySQL数据库的关键部分,生成Google Charts API需要的JSON对象,并使用JQuery和AJAX接收它.希望这点亮!


saf*_*rov 4

您可以传递数据,而json不是进行循环并传递data.setCell()

在 php 端将数据设置为 json 格式。使用json_encode()。在Api上使用这个方法来传递数据。检查此链接以获取更多信息

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