0

Is there a function in the Google Charts API similar to setColumns() that will work on JSON data?

I am trying to minimize PHP calls by combining my data into one array and then specifying to Google Charts which columns to use.

Using the code below I get the error that the function does not exist:

var data = new google.visualization.DataTable(jsonData);
data.setColumns([0,1,2]);

EDIT:

Here are the relevant portions of each file.

Javascript File:

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
      url: "getData.php",
      dataType:"json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

data.setColumns([0,1,2]);

var options = {
    width: chartWidth,
    height: chartHeight,
    backgroundColor: '#FFFFFF',
    legend:{
        textStyle:{color:'black'}
    },

    hAxis: {
      title: 'Time (EST)',
      baselineColor: 'black',
      textStyle:{color:'black',fontSize:'9'},
      slantedText: true,
      slantedTextAngle:45,
      titleTextStyle:{color:'black'}
    },

    vAxis: {
      title: 'Temperature(F)',
      baselineColor: 'black',
      textStyle:{color:'black'},
      titleTextStyle:{color:'black'}
    },

    colors: ['#FF0000', '#005F00']

  };

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.LineChart(document.getElementById('Tchart_div'));
  chart.draw(data, options);

Relevant PHP Code:

// Build an array thats Google Charts Readable ... ... ...
$table=array();
$table['cols'] = array(
    // Chart Labels (i.e. column headers)
    array('label' => 'dateTime', 'type' => 'string'),
    array('label' => 'Temp', 'type' => 'number'),
    array('label' => 'Dew', 'type' => 'number'),
    array('label' => 'Heat Index', 'type' => 'number'),
    array('label' => 'Wind Chill', 'type' => 'number'),
    array('label' => 'Pressure', 'type' => 'number'),
    array('label' => 'Radiation', 'type' => 'number'),
    array('label' => 'UV Index', 'type' => 'number'),
    array('label' => 'WindSpeed', 'type' => 'number'),
    array('label' => 'WindGustSpeed', 'type' => 'number')   
);

$rows = array();

while($r = mysql_fetch_assoc($query))
{
    $mdat = $r['dateTime'];
    if ( ($mdat % 900) == 0) // If it's within our interval, save the data
    {
        // Date/Time
        $tdat = new DateTime("@$mdat");
        $tdat->setTimeZone(new DateTimeZone('America/New_York'));
        $rdat = $tdat->format('H:i');

        //Temp/Dew
        $Tdat = $r['outTemp'];
        $Tdat = number_format($Tdat, 2, '.', '');
        $Ddat = $r['dewpoint'];
        $Ddat = number_format($Ddat, 2, '.', '');

        //Heat Index/Wind Chill
        $HIdat = $r['heatindex'];
        $HIdat = number_format($pdat, 2, '.', '');
        $WCdat = $r['windchill'];
        $WCdat = number_format($wdat, 2, '.', '');

        //Pressure
        $Pdat = $r['barometer'];
        if ($Pdat == 0)
        {
            $Pdat = 29.92;
        }
        $Pdat = $Pdat * 33.8637526;
        $Pdat = number_format($Pdat, 2, '.', '');

        //Solar
        $RADdat = $r['radiation'];
        $RADdat = number_format($RADdat, 2, '.', '');
        $Udat = $r['UV'];

        //Wind
        $Wdat = $r['windSpeed'];
        $Wdat = number_format($Wdat, 2, '.', '');
        $Gdat = $r['windGust'];

        // Now save everything in an array...
        $temp = array();
        $temp[] = array('v' => (string) $rdat);  //Time
        $temp[] = array('v' => (float) $Tdat);   //Temp
        $temp[] = array('v' => (float) $Ddat);   //Dewp
        $temp[] = array('v' => (float) $HIdat);  //Heat Index
        $temp[] = array('v' => (float) $WCdat);  //Wind Chill
        $temp[] = array('v' => (float) $Pdat);   //Pressure
        $temp[] = array('v' => (float) $RADdat); //Solar Radiation
        $temp[] = array('v' => (float) $Udat);   //UV Index
        $temp[] = array('v' => (float) $Wdat);   //Wind Speed
        $temp[] = array('v' => (float) $Gdat);   //Wind Gusts


        // Make the previous array a row in this new array
        $rows[] = array('c' => $temp);
    }
}

$table['rows'] = $rows; // Build a table out of the rows array
$jsonTable = json_encode($table); //encode the table into the json format

So in a nutshell, I want to tell the Charts API to only select certain fields from the JSON table

3
  • can you share the whole code for datatable? It might be an issue of asynchronous call. Oct 8, 2015 at 16:44
  • I added the relevant portions of the PHP and Javascript code
    – WxPilot
    Oct 8, 2015 at 17:26
  • easy way to hide columns --> create normal DataTable, use it to create DataView then hideColumns on the view, pass view to chart...
    – WhiteHat
    Oct 9, 2015 at 11:33

2 Answers 2

0

Instead of data.setColumns([0,1,2]);you should use setView.

data.setView({columns:[0,1,2]});

1
  • It appears that setView is exclusive to a chart wrapper object. Would it be easier (or more efficient) to switch to a wrapper in my case?
    – WxPilot
    Oct 9, 2015 at 15:42
0

You are probably looking for setColumns function of DataView Class. In that case the following example demonstrates how to set visible columns in Google Chart:

google.load("visualization", "1.1", { packages: ["table"] });
google.setOnLoadCallback(drawTable);

function drawTable() {
    
    getWeatherData(function (data) {
        var table = new google.visualization.Table(document.getElementById('table_div'));
        table.draw(data, { showRowNumber: true, width: '100%', height: '100%' });
    });
}



function getWeatherData(complete) {
    $.getJSON('https://gist.githubusercontent.com/vgrem/2d1436388ae8872f149d/raw/7193623c50cf2e093989391182aa67aaf8fdad2b/WeatherData.json', function (json) {
        var dataTable = new google.visualization.DataTable(json);
        var dataView = new google.visualization.DataView(dataTable);
        dataView.setColumns([0,1,2]);
        complete(dataView);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>

WeatherData.json

1
  • Can I use a null value into setColumns function? I´m trying to hide a column from a chart. Nov 20, 2019 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.