如何使用Javascript将多行数据放入图表中

时间:2016-01-14 23:29:25

标签: javascript sql

我无法弄清楚如何将多行SQL数据存入我的Google图表。

我已经将数据写入控制台(下面已注释),但是如何编写google图表代码以便为表格中的每一行写一个新数组?

例如,我希望对数据中的每一行重复以下代码:

[''+bridge_id_grab, +milemarker_grab, 0, '1', +bridge_health_grab]

完整代码:

var sql_statement3 = "SELECT bridge_id, bridge_health, milemarker FROM TABLE_NAME &api_key=MY_API_KEY&callback=?"
    $.getJSON('https://MY_USERNAME.cartodb.com/api/v2/sql/?q='+sql_statement3, function(data) {
      //console.log(data.rows);
      $.each(data.rows, function(key, val) {          
             for (i in data.rows) {             
                    var bridge_id_grab = [];                        
                    var bridge_health_grab = [];                        
                    var milemarker_grab = [];                       

                    bridge_id_grab.push(data.rows[i].bridge_id);                    
                    bridge_health_grab.push(data.rows[i].bridge_health);                    
                    milemarker_grab.push(data.rows[i].milemarker);  

                    //console.log(bridge_id_grab);
                    //console.log(bridge_health_grab);
                    //console.log(milemarker_grab);     

                     function corridor_chart() {

                            var data = google.visualization.arrayToDataTable([
                                    ['Bridge', 'MileMarker', '', '', 'Health'],
                                    [''+bridge_id_grab,    +milemarker_grab,     0,      '1',  +bridge_health_grab],
                                    [''+bridge_id_grab,    +milemarker_grab,     0,      '2',  +bridge_health_grab]
                            ]);

                              var options = {
                               "width": "100%",
                                            "legacyContinuousAxisRemoved": true,
                                            "chartArea": {
                                                "top": "0%",
                                                "left": "0%",
                                                "right": "0%",
                                                "width": "100%",
                                                "height": "80%"
                                            },
                                            "height": 180,
                                            "legend": "bottom",
                               title: '',
                               colors: ['#DB0000', '#FF0400', '#FF5500','#FF7C30', '#FFC431', '#FFF428', '#DCEA26', '#A7ED25', '#5DE207', '#00D300'],
                               "hAxis": {
                                 "useFormatFromData": true,
                                 "formatOptions": {},
                                 "textStyle": {
                                    "color": "none",
                                    "fontSize": 0
                                 },
                                 "viewWindow": {},
                                 "gridlines": {
                                    "color": "none",
                                    "count": "-1"
                                 },
                                 "titleTextStyle": {
                                    "color": "none",
                                    "fontSize": 0
                                 }
                              },
                                vAxis: {
                                title: "",
                                "gridlines": {
                                    "color": "none",
                                    "count": "0"
                                 },},
                                "bubble": {
                                 "textStyle": {
                                    "color": "blue",
                                    "fontSize": 11
                                 },
                                 "opacity": "1",
                                 "stroke": "#ffffff"
                              },
                              };

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

                            google.setOnLoadCallback(corridor_chart);                       
                }
            });
        });

根据darrylivan的答案编辑的代码&评论(它正在工作,虽然我仍然收到错误:'未捕获错误:不是数组'):

  var sql_statement3 = "SELECT bridge_id, bridge_health, milemarker FROM TABLE_NAME &api_key=MY_API_KEY&callback=?"
       $.getJSON('https://MY_USERNAME.cartodb.com/api/v2/sql/?q='+sql_statement3, function(data) {
                google.load('visualization', '1.0',  { 'packages': ['corechart', 'controls', 'bar'] });

                var chartData = [];
                chartData.push(  ['Bridge', 'MileMarker', '', '', 'Health'] )

                 for (var i = 0; i < data.rows.length; i++) 
                    {
                       var row = data.rows[i];
                       var dataRow = [ 
                          row.bridge_id.toString(), 
                          row.milemarker,
                          0, 
                          row.bridge_id.toString(),
                          row.bridge_health
                          ];

                        chartData.push( dataRow );
                        console.log(dataRow);
                    }

                    /* then call your charting func, but pass in the data
                      instead of computing it in that func.
                      */
                    corridor_chart( chartData );

                    function corridor_chart(chartData) {

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

                              var options = {
                               "width": "100%",
                                            "legacyContinuousAxisRemoved": true,
                                            "chartArea": {
                                                "top": "0%",
                                                "left": "0%",
                                                "right": "0%",
                                                "width": "100%",
                                                "height": "80%"
                                            },
                                            "height": 180,
                               title: '',
                                            "legend": "bottom",
                               colors: ['#DB0000', '#FF0400', '#FF5500','#FF7C30', '#FFC431', '#FFF428', '#DCEA26', '#A7ED25', '#5DE207', '#00D300'],
                               "hAxis": {
                                 "useFormatFromData": true,
                                 "formatOptions": {},
                                 "textStyle": {
                                    "color": "none",
                                    "fontSize": 0
                                 },
                                 "viewWindow": {},
                                 "gridlines": {
                                    "color": "none",
                                    "count": "-1"
                                 },
                                 "titleTextStyle": {
                                    "color": "none",
                                    "fontSize": 0
                                 }
                              },
                                vAxis: {
                                title: "",
                                "gridlines": {
                                    "color": "none",
                                    "count": "0"
                                 },},
                                "bubble": {
                                 "textStyle": {
                                    "color": "blue",
                                    "fontSize": 11
                                 },
                                 "opacity": "1",
                                 "stroke": "#ffffff"
                              },
                              };

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

1 个答案:

答案 0 :(得分:1)

在我看来,您需要在变量中构建数据数组,然后在图表选项定义中使用该变量。

所以,我假设你有一个json对象数组(也许是正确的,可能不是取决于数据的返回方式,但很可能......)

var sql_statement3 = "SELECT bridge_id, bridge_health, milemarker FROM TABLE_NAME &api_key=MY_API_KEY&callback=?";


$.getJSON('https://MY_USERNAME.cartodb.com/api/v2/sql/?q='+sql_statement3, function(data) {

// initialize your array
var chartData = [];

chartData.push(  ['Bridge', 'MileMarker', '', '', 'Health'] )


/* loop over sql data, and populate array
   you can be more compact about this, but
   this is a bit more readable...
*/
for (var i = 0; i < data.rows.length; i++) 
{
   var row = data.rows[i];
   console.log ( row);
   var dataRow = [ 
      row.bridge_id, 
      row.milemarker,
      0, 
      i.toString(),
      row.bridge_health
      ];

   chartData.push( dataRow );

}

/* then call your charting func, but pass in the data
  instead of computing it in that func.
  */
corridor_chart( chartData );

}

function corridor_chart( data ) {

  // don't compute data in here - it is passed in.
  //  ...


}

暂且不说:

你只需要一个迭代循环来构建这个数组 - 不是两个:

 $each(data.rows...) //   --OR--
 for (i in data.rows)

此外 - 如果您的数据以数组形式返回,则可能需要使用

for (var i = 0; i < data.rows.length; i++) .

如果您的数据作为对象返回,那么您提出的方法是hunky dory:

  for (row in data.rows)

后一个迭代循环实际上是用于迭代对象。