Search code examples
javascripttitaniumgoogle-visualizationtitanium-mobile

Google Charts doesn't display data


I'm making an App with Titanium Studio, and tried to use a webView and Google Charts to Visualize some data. The data is in an two-dimensional array, like so:

[["Tendency","Number of Answers"],["Item one", 2],["Item two", 5]]

This is the code I use to pass the data:

function Graph(data){
var chart = Ti.UI.createWebView({
    url: "/results.html",
    width: Ti.UI.SIZE,
    height: "auto",
    top: 110
});

for (var i=0, l=data.length; i<l; i++){
    if (data[i] instanceof Array) data[i] = data[i].join(";");
}
var syndata = data.join("@");

chart.addEventListener('beforeload',function(e){
    chart.evalJS("var syndata ='"+syndata+"';");
});

this.chart = chart;

return;
};

module.exports = Graph;

I tried passing different kinds of data, and found that it only works with strings, so I converted the array to a string of "Tendecy;Number of answers@Item1;2@...." In the results.html, I convert it to an array again, and read it into the chart:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var dt = syndata.split("@");
for(var i = 0, l = dt.length; i<l; i++) dt[i] = dt[i].split(";");

  google.load("visualization", "1", {packages:["corechart"]});
  function drawChart(d) {

    var data = google.visualization.arrayToDataTable(d);

    var options = {
      title: 'Overview',
      chartArea:{left:5,top:5,width:"100%",height:"100%"}
    };

    var chart = new google.visualization.PieChart(document.getElementById('chart'));
    chart.draw(data, options);
  }

  google.setOnLoadCallback(function(){ drawChart(dt) });
</script>

However, I only get a grey chart with one item saying "Other". It works fine when I paste the array directly into the file and reference from that... I tried outputting the array with Ti.API.info directly from results.html to see if there was a mistake, but everything seems fine. Any ideas?


Solution

  • http://blog.clearlyinnovative.com/post/4044172191/titanium-appcelerator-quickie-google-charts-and