6

I am attempting to create multiple Google Charts, but I can't get it to work. I've tried everything I could find on Stack Overflow. I most recently attempted this fix, but it didn't work. I think I may be missing something. Can anyone see anything wrong with the code as it stands now?

Expected Behavior:

Page displays bar graph. Then, a line graph is displayed underneath the bar graph.

Current Behavior:

Page displays bar graph. Line graph does not display.

Here is JSFiddle. On a side note, the JavaScript only seems to work inline on JSFiddle. If I moved it into the JavaScript section, it did not function properly. Maybe this has something to do with the external resource that was called?

Regardless, I am currently doing this all inline for this experiment.

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="https://www.google.com/jsapi" type="text/javascript">
    </script>
    <script type="text/javascript">
    // Load the Visualization API and the chart packages.
    google.load('visualization', '1.1', {
        packages: ['line', 'bar', 'corechart']
    });
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    // Callback that creates and populates a data table,
    // instantiates the charts, passes in the data and
    // draws them.
    function drawChart() {
        // Create the data table.
        var BarData = new google.visualization.arrayToDataTable([
            ['', 'Customer', 'Segment Avg'],
            ['TTM Sales', 4, 2],
            ['TTM Orders', 5, 3],
            ['TTM Categories', 7, 4]
        ]);
        // Create the data table.
        var LineData = new google.visualization.arrayToDataTable([
            ['Year', 'Customer', 'Segment Avg'],
            ['2011', 4, 5],
            ['2012', 5, 3],
            ['2013', 4, 2]
        ]);
        // Set chart options
        var BarOptions = {
            chart: {
                title: 'Performance',
            },
            width: 900,
            height: 500
        };
        // Set chart options
        var LineOptions = {
            chart: {
                title: 'Sales History'
            },
            width: 900,
            height: 500
        };
        // Instantiate and draw our chart, passing in some options.
        var BarChart = new google.charts.Bar(document.getElementById(
            'bar_chart'));
        BarChart.draw(BarData, BarOptions);
        var LineChart = new google.charts.Line(document.getElementById(
            'line_chart'));
        LineChart.draw(LineData, LineOptions);
    };
    </script>
    <title>Test Chart Page</title>
</head>
<body>
    <!--Divs that will hold the charts-->
    <div id="bar_chart"></div>
    <div id="line_chart"></div>
</body>
</html>
2
  • the issue is related to timing. here is working fork of your fiddle with timeout separating the execution of the two charts. jsfiddle.net/m7mn72e2
    – CodeToad
    Oct 14, 2015 at 14:32
  • note also that in the failing test case, child elements are added by googlecharts code to both divs.
    – CodeToad
    Oct 14, 2015 at 14:33

4 Answers 4

8

It seems some changes have been made in the latest version of Google Charts API that causes this behavior, but there is a reliable way to render multiple charts on a single page. The idea is to render the next chart once the previous one is rendered, for that purpose you could utilize ready event handler.

Having said that, replace

var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
barChart.draw(barData, barOptions);
var lineChart = new google.charts.Line(document.getElementById('line_chart'));
lineChart.draw(lineData, lineOptions);

with

var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
google.visualization.events.addOneTimeListener(barChart, 'ready', function () {
      var lineChart = new google.charts.Line(document.getElementById('line_chart'));
      lineChart.draw(lineData, lineOptions);
});
barChart.draw(barData, barOptions);

Working example

google.load('visualization', '1.1', {
        packages: ['line', 'bar', 'corechart']
    });
    // Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);

function drawCharts() {
    // Create the data table.
    var barData = new google.visualization.arrayToDataTable([
        ['', 'Customer', 'Segment Avg'],
        ['TTM Sales', 4, 2],
        ['TTM Orders', 5, 3],
        ['TTM Categories', 7, 4]
    ]);
    // Create the data table.
    var lineData = new google.visualization.arrayToDataTable([
        ['Year', 'Customer', 'Segment Avg'],
        ['2011', 4, 5],
        ['2012', 5, 3],
        ['2013', 4, 2]
    ]);
    // Set chart options
    var barOptions = {
        chart: {
            title: 'Performance',
        },
        width: 900,
        height: 500
    };
    // Set chart options
    var lineOptions = {
        chart: {
            title: 'Sales History'
        },
        width: 900,
        height: 500
    };


    var barChart = new google.charts.Bar(document.getElementById('bar_chart'));
    google.visualization.events.addOneTimeListener(barChart, 'ready', function () {
        var lineChart = new google.charts.Line(document.getElementById('line_chart'));
        lineChart.draw(lineData, lineOptions);
    });
    barChart.draw(barData, barOptions);
};
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<div id="bar_chart"></div>
<div id="line_chart"></div>

2
  • Is there a benefit to using this method as opposed to using the setTimeout function? Oct 14, 2015 at 15:21
  • 2
    In my opinion it is more reliable way .In case of setTimeout there is no guarantee that chart will get rendered since the specified delay does not correspond to the time when first chart is rendered Oct 14, 2015 at 15:35
2

Works with setTimeout:

// Instantiate and draw our chart, passing in some options.
var BarChart = new google.charts.Bar(document.getElementById(
    'bar_chart'));
setTimeout(function() {
  BarChart.draw(BarData, BarOptions);
}, 0);
var LineChart = new google.charts.Line(document.getElementById(
    'line_chart'));
setTimeout(function() {
  LineChart.draw(LineData, LineOptions);
}, 1e3);

Updated JSFiddle

1

The code below works by creating the second chart inside of setTimeout. I don't know what is causing the problem, but at least you have a workaround.

fiddle

<script type="text/javascript">
    // Load the Visualization API and the chart packages.
    google.load('visualization', '1.1', {
        packages: ['line', 'bar', 'corechart']
    });
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    // Callback that creates and populates a data table,
    // instantiates the charts, passes in the data and
    // draws them.
    function drawChart() {
        // Create the data table.
        var BarData = new google.visualization.arrayToDataTable([
            ['', 'Customer', 'Segment Avg'],
            ['TTM Sales', 4, 2],
            ['TTM Orders', 5, 3],
            ['TTM Categories', 7, 4]
        ]);
        // Create the data table.
        var LineData = new google.visualization.arrayToDataTable([
            ['Year', 'Customer', 'Segment Avg'],
            ['2011', 4, 5],
            ['2012', 5, 3],
            ['2013', 4, 2]
        ]);
        // Set chart options
        var BarOptions = {
            chart: {
                title: 'Performance',
            },
            width: 900,
            height: 500
        };
        // Set chart options
        var LineOptions = {
            chart: {
                title: 'Sales History'
            },
            width: 900,
            height: 500
        };
        // Instantiate and draw our chart, passing in some options.
        var BarChart = new google.charts.Bar(document.getElementById(
            'bar_chart'));

        var LineChart = new google.charts.Line(document.getElementById(
            'line_chart'));
        LineChart.draw(LineData, LineOptions);
        setTimeout(function(){


        BarChart.draw(BarData, BarOptions);
    },50);

        };
    </script>
    <body>
        <!--Divs that will hold the charts-->
        <div id="bar_chart"></div>
        <div id="line_chart"></div>
    </body>
4
  • This is perfect. As I've continued my reading, I've seen a couple of people say that there are issues with multiple charts in Google Charts. But, this definitely takes care of the issue. Thanks! Oct 14, 2015 at 14:37
  • I will accept the answer in 5 minutes when it allows me to do so. Oct 14, 2015 at 14:37
  • 1
    How does this compare to Vadim's solution of using the the ready event handler? I want to ensure that I'm using the best solution. In my head, the ready handler makes more sense, as it is tied directly to the previous function rather than an abstract delay that we select. Oct 14, 2015 at 15:24
  • 1
    Indeed, the ready handler is a better approach. The timeout was suggested as a workaround until a more precise solution is available.
    – CodeToad
    Oct 18, 2015 at 11:14
1

Google fixed this timing issue in a recent release, available with the frozen version loader: https://developers.google.com/chart/interactive/docs/library_loading_enhancements#frozen-versions

Relevant thread: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/google-visualization-api/KulpuT418cg/yZieM8buCQAJ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.