Google Charts可变范围问题

时间:2013-11-19 16:18:52

标签: javascript api google-visualization

尝试制作Google Charts信息中心,但我遇到了一些简单代码的麻烦,这让我很生气。我认为它与变量范围有关。

以下是我用于从Google教程制作简单图表的代码:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type = 'text/javascript'>
        var options = {
      width: 400,
      height: 240,
      vAxis: {minValue:0, maxValue:1000},
      animation: {
        duration: 1000,
        easing: 'out'
      }
    };

       var chart = new google.visualization.ColumnChart(
           document.getElementById('chart_div'));
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'x');
        data.addColumn('number', 'A');
        data.addColumn('number', 'B');
        data.addRow(['A', 123, 40]);
        data.addRow(['B', 17, 20]);
        var addButton = document.getElementById('unique');
        function drawChart() {
          // Disabling the buttons while the chart is drawing.
          addButton.disabled = true;
          google.visualization.events.addListener(chart, 'ready',
              function() {
                // Enabling only relevant buttons.
                addButton.disabled = (data.getNumberOfColumns() - 1) >= chars.length;
              });
          chart.draw(data, options);
        }
        function shuffleAndDrawChart() {
          for (var i = 0; i < data.getNumberOfRows(); ++i) {
            for (var j = 1; j < data.getNumberOfColumns(); ++j) {
              var num = Math.floor(Math.random() * 1000);
              data.setValue(i, j, num);
            }
          }
          drawChart();
        }
        addButton.onclick = function() {
          data.addColumn('number', chars[data.getNumberOfColumns() - 1]);
          shuffleAndDrawChart();
        }
        drawChart();     
    </script>

    <title>Light Blue - Admin Template</title>
    <link href="css/application.css" rel="stylesheet">
    <link rel="shortcut icon" href="img/favicon.png">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <?php
        require_once 'includes/ga/src/Google_Client.php';
        require_once 'includes/ga/src/contrib/Google_AnalyticsService.php';
        require_once 'includes/ga/src/contrib/Google_PlusService.php';
        require_once 'includes/gaConnect.php';
        require_once 'includes/functions.php';

        if (!$client->getAccessToken()) 
            {
            $authUrl = $client->createAuthUrl();
            exit("<a class='login' href='$authUrl'>Connect Me!</a>");
            }
        else 
            {
            $analytics = new Google_AnalyticsService($client);

            $lastmonth = date('Y') . "-" . (date('m')-1) . "-" . date('d');
            $yesterday = date('Y') . "-" . date('m') . "-" . (date('d')-1);

            $visitsOverTime = runQuery($analytics, 'ga:visits', $lastmonth, $yesterday, 'ga:date');
            $totalVisits = runQuery($analytics, 'ga:visits', $lastmonth, $yesterday, NULL);

            $uniqueOverTime = runQuery($analytics, 'ga:visitors', $lastmonth, $yesterday, 'ga:date');
            $totalUnique = runQuery($analytics, 'ga:visitors', $lastmonth, $yesterday, NULL);

            $pageviewsOverTime = runQuery($analytics, 'ga:pageviews', $lastmonth, $yesterday, 'ga:date');
            $totalPageviews = runQuery($analytics, 'ga:pageviews', $lastmonth, $yesterday, NULL);

            $bounceRateOverTime = runQuery($analytics, 'ga:visitBounceRate', $lastmonth, $yesterday, 'ga:date');
            $totalBounceRate = runQuery($analytics, 'ga:visitBounceRate', $lastmonth, $yesterday, NULL);

            $newVisitsOverTime = runQuery($analytics, 'ga:percentNewVisits', $lastmonth, $yesterday, 'ga:date');
            $totalNewVisits = runQuery($analytics, 'ga:percentNewVisits', $lastmonth, $yesterday, NULL);

            $avgTimeOverTime = runQuery($analytics, 'ga:avgTimeOnSite', $lastmonth, $yesterday, 'ga:date');
            $totalAvgTime = runQuery($analytics, 'ga:avgTimeOnSite', $lastmonth, $yesterday, NULL);
            }
    ?>
    <meta charset="utf-8">
</head>

问题是这段代码(直接从Google Dev网站上复制/粘贴)不起作用!!我不知道为什么!!!! 这段代码唯一适用于我的方法是将所有变量声明放在drawChart()函数中。否则,我最终得到一个空白画布,没有图表。

这是非常令人沮丧的,自从星期四以来我一直试图弄清楚这个问题。它正在从内到外慢慢地杀了我,如果我不知道的话,我想我可能会做一些激烈的事情。

请帮忙!我每天都陷入越来越深的抑郁症和酗酒状态,我不知道这个问题。

- 编辑 -

我被告知要检查控制台是否有任何JavaScript或HTML错误。我运行了FireBug JavaScript控制台,发现没有错误。如果有更好的方法,请告诉我。我仍然是JavaScript的新手。

1 个答案:

答案 0 :(得分:0)

首先,您缺少Google加载器,因此可视化API永远不会加载。其次,设置代码的方式,在加载API之前尝试创建可视化元素时会遇到问题。您需要将所有图表代码包装在另一个函数中,并将该函数用作来自Google加载器的回调。它看起来像这样:

function initialize () {
    var options = {
        width: 400,
        height: 240,
        vAxis: {minValue:0, maxValue:1000},
        animation: {
            duration: 1000,
            easing: 'out'
        }
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'x');
    data.addColumn('number', 'A');
    data.addColumn('number', 'B');
    data.addRow(['A', 123, 40]);
    data.addRow(['B', 17, 20]);
    var addButton = document.getElementById('unique');
    function drawChart() {
        // Disabling the buttons while the chart is drawing.
        addButton.disabled = true;
        google.visualization.events.addListener(chart, 'ready', function() {
            // Enabling only relevant buttons.
            addButton.disabled = (data.getNumberOfColumns() - 1) >= chars.length;
        });
        chart.draw(data, options);
    }
    function shuffleAndDrawChart() {
        for (var i = 0; i < data.getNumberOfRows(); ++i) {
            for (var j = 1; j < data.getNumberOfColumns(); ++j) {
                var num = Math.floor(Math.random() * 1000);
                data.setValue(i, j, num);
            }
        }
        drawChart();
    }
    addButton.onclick = function() {
        data.addColumn('number', chars[data.getNumberOfColumns() - 1]);
        shuffleAndDrawChart();
    }
    drawChart();
}
google.load('visualization', '1', {packages:['corechart'], callback: initialize});