fusionTables to htmlTable

by FiNGAHOLiC

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://www.google.com/jsapi"></script> 
<script> google.load('visualization', '1', {}); </script>

<p><a href="http://www.google.com/fusiontables/DataSource?dsrcid=590460" target="_blank">see this data on fusion tables</a></p>

<table>
<thead id="thead"></thead>
<tbody id="tbody"></tbody>
</table>

CSS

p{
    padding:0 0 20px;
}
th,td{
    border:1px solid #000;
    padding:4px 10px;
}
thead th{
    background:#ddd;
}

JavaScript

function requestData() {

    // fusion tables data: 

    var queryText = encodeURIComponent("SELECT 'date','used' FROM 590460");
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='    + queryText);

    query.send(function(response){

        var numRows = response.getDataTable().getNumberOfRows();
        var numCols = response.getDataTable().getNumberOfColumns();

        var $tbody = $('#tbody');

        /* thead */

        var $thead = $('#thead');
        var $tr = $('<tr />');
        _(numCols).times(function(i){
            var val = response.getDataTable().getColumnLabel(i);
            $('<th />',{ text: val }).appendTo($tr);
        });
        $tr.appendTo($thead);

        /* tbody */

        _(numRows).times(function(i){
            var $tr = $('<tr />');
            _(numCols).times(function(j){
                var val = response.getDataTable().getValue(i, j);
                if($.type(val) === 'date'){
                    val = val.getFullYear() + '/' + val.getMonth() + '/' + val.getDate();
                }
                $('<td />',{ text: val }).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });

    });
}

/* do */

$(requestData);