0

I'm trying to draw two Google Charts on the same webpage.

The code for the 2nd chart looks like this

function chart2() {
  /* second chart (scatter plot) */
  var data2 = new google.visualization.DataTable();
  data2.addColumn('number', 'Date');
  data2.addColumn('number', 'Sold Price');

  var map = /*[[${worthTemplateData.pricingInfo['marketHistory']}]]*/ [];
  map.forEach(function (item) {
     data2.addRows([ [item.date, item.origPrice] ]);
  });

  alert('Please wait');

  var options = {
     width: 900,
     height: 500,
     chart: {
     title: 'Price History',
     subtitle: 'For similar-size units'
     },
     hAxis: {title: 'Date'},
     vAxis: {title: 'Sold Price'}
  };

  var chart2 = new google.charts.Scatter(document.getElementById('google-chart2'));
     chart2.draw(data2, google.charts.Scatter.convertOptions(options));
}

It works.

But as soon as I remove the alert('Please wait'); line, it doesn't work anymore! The screen area where the chart should be is empty.

I suspect there is some timing issue, even though JS is presumably "single-threaded".

What's more puzzling, if I change the order, only the other chart loads:

google.load("visualization", "1.0", {packages: ["bar", "scatter"]});
google.setOnLoadCallback(drawCharts);

function drawCharts() {
        chart2();
        chart1();
}

What's the fix?

Alex R
  • 11,364
  • 15
  • 100
  • 180

1 Answers1

0

There is an issue with drawing multiple material charts. You could switch to Classic Scatter Charts: google.charts.Scatter -> google.visualization.ScatterChart or try with some delay:

function doSetTimeOutDrawChart(chart, data, options, delay){
    setTimeout(function () { 
        chart.draw(data, options);
    }, delay);
} 

like in this example: jsFiddle

Milan Rakos
  • 1,705
  • 17
  • 24
  • Another solution from [WhiteHat](http://stackoverflow.com/users/5090771/whitehat) -> [here](http://stackoverflow.com/questions/32884121/google-charts-drawing-multiple-bar-charts-with-dual-axis-in-ie/32907208#32907208) – Milan Rakos Nov 07 '15 at 23:11
  • for 1st suggestion, I got error -- TypeError: google.visualization.ScatterChart is not a constructor – Alex R Nov 08 '15 at 15:01
  • you need to load `google.load("visualization", "1", {packages:["corechart"]` – Milan Rakos Nov 08 '15 at 15:53
  • I tried that, it didn't work. For now I've decided to just remove one of the charts. – Alex R Nov 08 '15 at 16:55
  • You could post your complete code regarding charts or provide jsFiddle link. – Milan Rakos Nov 08 '15 at 20:06