1
votes

I'm looking for sample code for using a Google Sheet as the source data and make a fairly simple line chart using Google Visualization.

I noticed that the new Google Sheets don't include a script in the "Share Chart" function, they offer a IFRAME and the width/height doesn't work. So, I'm looking to do it with Google Visualizations.

Here is my sample chart.

Thank you for the help.

Edited...

Here is my spreadsheet.

Here is my HTML file.

<html>

<head>
    <script type="text/javascript">
        function drawChart() {
            var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key=14MXilv-uhEAUxDzVB7qVCCmQYqkmWvqqaBOXeBsS04k&gid=0');
            query.setQuery('SELECT A, B, C, D, E');
            query.send(function (response) {
                if (response.isError()) {
                    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
                    return;
                }

                var data = response.getDataTable();

                var chart = new google.visualization.LineChart(document.querySelector('linechart'));
                chart.draw(data, {
                    height: 400,
                    width: 600
                });
            });
        }
        google.load('visualization', '1', {
            packages: ['corechart'],
            callback: drawChart
        });
    </script>

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

<body>
    <span id="linechart"></span>
</body>

</html>

It doesn't draw. I've tried various selection in the spreadsheet like avoiding column A, no go. What am I doing wrong?

1

1 Answers

1
votes

Here's some example code to get you started:

function drawChart() {
    var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key={spreadsheet key}&gid=0');
    query.setQuery('SELECT A, B, C');
    query.send(function (response) {
        if (response.isError()) {
            alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
            return;
        }

        var data = response.getDataTable();

        var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
        chart.draw(data, {
            height: 400,
            width: 600
        });
    });
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});

You would need to replace the {spreadsheet key} in the URL with your own spreadsheet key (eg: 'http://docs.google.com/spreadsheet/tq?key=1234567890&gid=0') and change the query to select the appropriate columns from your spreadsheet.

In your page's HTML, you need to have a container div that matches the ID used when creating the chart ('chart_div' in this case):

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