How to generate two Google Charts on the same page?

Asked

Viewed 878 times

1

I know that the code below generates 1 graph inside the page but I need to generate several graphs and I do not know the logic used to achieve, dynamically, the goal. Can you help me please?

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
  // Load the Visualization API and the corechart package.
  google.charts.load('current', {
    'packages': ['corechart']
  });

  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    // Set chart options
    var options = {
      'title': 'How Much Pizza I Ate Last Night',
      'width': '100%',
      'height': 'auto'
    };

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>
<div id="chart_div"></div>

1 answer

1

What defines where the graphic will be presented is precisely the document.getElementById('chart_div'), specified on the last lines.


Assuming you are using Jquery, you could create new elements and then point to it, a quick example would be:

$(document).ready(function() {
  google.charts.load('current', {
    'packages': ['corechart']
  });

  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    // Set chart options
    var options = {
      'title': 'How Much Pizza I Ate Last Night',
      'width': '100%',
      'height': 'auto'
    };

    // Instantiate and draw our chart, passing in some options.

    for (i=0; i < 5; i++){
      $('.v-graficos').append('<div class="x-grafico"></div>');

      var chart = new google.visualization.PieChart($('.x-grafico').last()[0]);
      chart.draw(data, options);
    }
  }
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<div class="v-graficos"></div>

This will create five charts due to the loop, which creates element and sets to create the chart within the last created element. Of course, in this case would create with the same values previously defined.


If it is dynamic, the data probably comes from a server and there is a example on google itself.

Supposing there are two Graphics, one for https://site.com/estoque and another to https://site.com/visitas, then:

$(document).ready(function() {

  // Para simular requisições:
  $.mockjax({
    url: "/estoque",
    responseText: {
      "cols": [
            {"id":"","label":"Topping","pattern":"","type":"string"},
            {"id":"","label":"Slices","pattern":"","type":"number"}
          ],
      "rows": [
            {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
            {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
            {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
            {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
            {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
          ]
    }
  });
  $.mockjax({
    url: "/visitas",
    responseText: {
      "cols": [
            {"id":"","label":"Topping","pattern":"","type":"string"},
            {"id":"","label":"Slices","pattern":"","type":"number"}
          ],
      "rows": [
            {"c":[{"v":"Homens","f":null},{"v":100,"f":null}]},
            {"c":[{"v":"Mulheres","f":null},{"v":100,"f":null}]},
          ]
    }
  });
  ////////////////////////////
  
  google.charts.load('current', {
    'packages': ['corechart']
  });

  google.charts.setOnLoadCallback(function() {
    drawChart(['/estoque', '/visitas']);
  });

});


function drawChart(endpoints) {

  $.each(endpoints, function(_, url){
  
    var jsonData = $.ajax({
            url: url,
            dataType: "json",
            async: false
            }).responseText;
 
     $('.v-graficos').append('<div class="x-grafico"></div>');

     var data = new google.visualization.DataTable(jsonData);
     var chart = new google.visualization.PieChart($('.x-grafico').last()[0]);
     chart.draw(data, {width: 400, height: 240});
     console.clear();
  });
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.js"></script>

<div class="v-graficos"></div>

In the example above the excerpt:

google.charts.setOnLoadCallback(function() {
   drawChart(['/estoque', '/visitas']);
});

Sets the path where JSON will be, see the documentation to see how it should be formatted. Within the drawChart is doing ajax in this case. This could also be the reverse, could just do function drawChart(result){} and inform the result ajax.

For each new request (which is defined in ['/estoque', '/visitas']) a new element will also be created and this last element created will be where the graph will appear.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.