Kantine
Kantine

Reputation: 67

HTML Google chart with value argument in Javascript

I try to display a google chart in HTML using an argument from Javascript. my code is the following:

HTML file chart.html:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="chart.js"></script>
<div id="chart_div"></div>
<script>
    google.charts.load('current', {packages: ['corechart', 'bar']});
    google.charts.setOnLoadCallback(drawBasic);
    drawBasic(1500000);
</script>

JavaScriptFile chart.js:

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);

function getData(number) {
    var data = google.visualization.arrayToDataTable([
        ['City', '2010 Population',],
        ['New York City, NY', 8175000],
        ['Los Angeles, CA', 3792000],
        ['Chicago, IL', 2695000],
        ['Houston, TX', 2099000],
        ['Philadelphia, PA', number]
      ]);
    return data;
}

function getOptions () {
    var options = {
        title: 'Population of Largest U.S. Cities',
        chartArea: {width: '50%'},
        hAxis: {
          title: 'Total Population',
          minValue: 0
        },
        vAxis: {
          title: 'City'
        }
      };
    return options;
}

function drawBasic(number) {

      var data = getData(number);

      var options = getOptions();

      var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

      chart.draw(data, options);
    }

The chart is loaded but the bar for Philadelphia is missing. I noticed that removing this part

<script>
      google.charts.load('current', {packages: ['corechart', 'bar']});
      google.charts.setOnLoadCallback(drawBasic);
      drawBasic(1500000);
 </script>

in chart.html doesn't change the behavior. I conclude the chart is loaded right after the

<script type="text/javascript" src="chart.js"></script>

line with no argument for number. How can I give my argument number to my chart ?

Upvotes: 1

Views: 239

Answers (1)

WhiteHat
WhiteHat

Reputation: 61275

you need to wait for google charts to load,
before drawing a chart.

which is the point of --> setOnLoadCallback

you pass a function to this method,
which will be called when google charts has fully loaded.

here, drawBasic is called with the argument,
before google charts has loaded, and it fails.

then drawBasic is called again from the callback,
but it doesn't have the argument, so no bar for Philadelphia

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
drawBasic(1500000);

instead, use an anonymous function to pass the argument...

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(function () {
  drawBasic(1500000);
});

note: unless you plan to use a material bar chart --> google.charts.Bar
you don't need the 'bar' package...

Upvotes: 1

Related Questions