How to generate two Google Charts on the same page?

0

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

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script>//LoadtheVisualizationAPIandthecorechartpackage.google.charts.load('current',{'packages':['corechart']});//SetacallbacktorunwhentheGoogleVisualizationAPIisloaded.google.charts.setOnLoadCallback(drawChart);//Callbackthatcreatesandpopulatesadatatable,//instantiatesthepiechart,passesinthedataand//drawsit.functiondrawChart(){//Createthedatatable.vardata=newgoogle.visualization.DataTable();data.addColumn('string','Topping');data.addColumn('number','Slices');data.addRows([['Mushrooms',3],['Onions',1],['Olives',1],['Zucchini',1],['Pepperoni',2]]);//Setchartoptionsvaroptions={'title':'HowMuchPizzaIAteLastNight','width':'100%','height':'auto'};//Instantiateanddrawourchart,passinginsomeoptions.varchart=newgoogle.visualization.PieChart(document.getElementById('chart_div'));chart.draw(data,options);}</script><divid="chart_div"></div>
    
asked by anonymous 18.09.2017 / 02:15

1 answer

0

What defines where the graph will appear is just the document.getElementById('chart_div') , specified in 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><scripttype="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><divclass="v-graficos"></div>

This will create five graphs because of the loop, which creates element and sets to create the graph within the last created element. Of course, in this case I would create with the same values previously defined.

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

Assuming there are two graphs, one for https://site.com/estoque and one for 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><scripttype="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.js"></script><divclass="v-graficos"></div>

In the example above the excerpt:

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

Set the path to where JSON will be, view the documentation to see how it should be formatted . Within drawChart is doing ajax, in this case. This could also be the other way around, you could just do function drawChart(result){} and report the result of ajax.

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

    
18.09.2017 / 04:21