Ian
Ian

Reputation: 6124

Using a variable as a value in Google Charts (Gauge)

I am trying to dynamically update a value in a Google Charts Gauge, but when I try and use a variable as the value, it breaks.

var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    //Doesn't work:
    ['Barometer', x],
    //Works:
    [x, 28],
    //Works:
    ['Barometer', 28]
    ]);

The problem is the way that I am declaring the variable, I think, because when I just use var x=28, it works fine. Here is the code I am using to get the variable: It uses Jquery to fetch a JSON file, and takes a value from the file:

var x
    $.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?',
        function(data){
            x = data.value.items[0].data[1].parameters.pressure.value;
        }
    )

I tried using x = eval(x), but it still didn't wok at all. However, when I used x = eval(x+1-1) or x = x+1-1, the gauge showed up, but the value was NaN.

Upvotes: 2

Views: 6352

Answers (1)

Ian
Ian

Reputation: 6124

OK, solved it.

I ended up defining the variable before loading the Google Charts API, and then, right before defining the variable, I added x = eval(x).

So here is the final, simplified code:

var x
$.getJSON('insert JSON url here WITH QUOTES',
    function(data){
        x = path.to.something.in.JSON.file.here;
    }

google.load('visualization', '1', {
    packages: ['gauge']
});
google.setOnLoadCallback(drawChart);

function drawChart() {

    x = eval(x)
    var Data = google.visualization.arrayToDataTable([
        ['Label', 'Value'],
        ['Gauge', x],
        ]);

    var Options = {
    };

    var Chart = new google.visualization.Gauge(document.getElementById('insertGaugeContainerHere'));
    Chart.draw(Data, Options);
}

In case you're wondering, the final product is located here.

Upvotes: 2

Related Questions