Showing posts with label Motion Chart. Show all posts
Showing posts with label Motion Chart. Show all posts

Sunday, June 6, 2010

Google Motion Chart using XML datasource

Gooogle Motion Chart using XML as data source

A dynamic chart to explore several indicators over time. The chart is rendered within the browser using Flash.

XML is used as datasource for motion chart instead of google spreadsheet.

<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['motionchart']});
google.setOnLoadCallback(getXMLData);

function getXMLData() {
url = "XML data url here"
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = drawChartData;
try {
req.open("GET", url, true);
} catch (e) {
alert("Problem : " + e);
}
req.send();
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = drawChartData;
req.open("GET", url, true);
req.send();
}
}
}

function drawChartData() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var reqResponse = req.responseXML;
var xmlItems = reqResponse.getElementsByTagName("item")
//alert(xmlItems[i].getElementsByTagName("item1")[0].childNodes[0].nodeValue);
var data = new google.visualization.DataTable();
data.addColumn("string", "Country");
data.addColumn('date', 'Year');
data.addColumn('number', 'Projects');
data .addRows(xmlItems.length);

for (var i = 0; i < xmlItems.length; i++) {
//alert(xmlItems[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
data .setCell(i, 0, xmlItems[i].getElementsByTagName("country")[0].childNodes[0].nodeValue);
data .setCell(i, 1, new Date(xmlItems[i].getElementsByTagName("year")[0].childNodes[0].nodeValue));
data .setCell(i, 2, Number(new Number(xmlItems[i].getElementsByTagName("projects")[0].childNodes[0].nodeValue)));
}
//alert(data.getValue(0,0));
var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(data, {width: (screen.availWidth-50), height:(screen.availHeight-250)});
}

} else {
//alert("Problem: " + req.statusText);
}
}
</script>
</head>

<body>

<div id="chart_div" width="100%" height="90%">
<table width="100%" height="100%"><tr><td height="80%" width="100%" align="center" valign="center">
<img src="Loading Image URL"></img>
</td></tr></table>
</div>
</body>
</html>

******************

XML format shoule be as shown below

<items>
<item>
<country>India</country>
<year>12/24/2009</year>
<projects>2000<projects/>
</item>
<item>
<country>USA</country>
<year>12/24/2009</year>
<projects>4000<projects/>
</item>
</items>

Search This Blog