添加类别过滤器到谷歌可视化API

时间:2014-01-01 10:09:49

标签: javascript google-visualization google-sheets

我是谷歌图表可视化的新手。我使用“谷歌电子表格”作为我的图表的数据源,但是当我尝试添加过滤器类别时,我似乎无法控制并合并谷歌游戏中的两个示例

这就是我展示饼图的方式:

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
  var query = new google.visualization.Query(
      'http://spreadsheets.google.com/tq?key=0ArCLNmjk_GPpdHVZbVVuUlNKUF9TTHlpaWxPY1dmUnc&range=B1:C4&pub=1');

  query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }

  var data = response.getDataTable();
  var chart = new google.visualization.PieChart(document.getElementById('columnchart'));
  chart.draw(data, null);
}
</script>

<title>Data from a Spreadsheet</title>
</head>

<body>
<span id='columnchart'></span>
</body>
</html>​

我在电子表格中的第一个范围(COLUMN A)有“类别”的定义,我想将过滤器添加到我的图表中。

1 个答案:

答案 0 :(得分:3)

您需要解决以下几个问题:首先,您的查询仅限于电子表格中的两列(B1:C4,均称为“计数”),但不包括控件。其次,图表的容器应该是div,而不是span。第三,为了使用控件,您需要为图表使用ChartWrapper,并且必须为API提供“controls”包。这是一个有效的代码示例:

[JavaScript的]

function drawChart() {
    var query = new google.visualization.Query('http://spreadsheets.google.com/tq?key=0ArCLNmjk_GPpdHVZbVVuUlNKUF9TTHlpaWxPY1dmUnc&pub=1');

    query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
    if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
    }

    var data = response.getDataTable();

    var control = new google.visualization.ControlWrapper({
        containerId: 'control_div',
        controlType: 'CategoryFilter',
        options: {
            filterColumnIndex: 0,
            ui: {

            }
        }
    });

    var chart = new google.visualization.ChartWrapper({
        containerId: 'chart_div',
        chartType: 'PieChart',
        options: {
            height: 400,
            width: 600
        },
        view: {
            columns: [0, 1]
        }
    });

    var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard'));
    dashboard.bind([control], [chart]);
    dashboard.draw(data);
}
google.load('visualization', '1', {packages:['controls'], callback: drawChart});

[HTML]

<div id="dashboard">
    <div id="control_div"></div>
    <div id="chart_div"></div>
</div>

在此处查看:http://jsfiddle.net/asgallant/rS4L8/