Ryder Brooks
Ryder Brooks

Reputation: 2119

google visualization getColumnId

I have a dataTable with several columns. I'm building a chart from a view of this dataTable. When an item from the legend of the chart is clicked I'd like to get the column of the underlying dataTable.

Code:

var score_select = google.visualization.events.addListener(score_chart, 'select', function(){
        var chrt = score_chart.getChart().getSelection()[0].column;//I'm using a chartWrapper
        var dt = score_chart.getDataTable().getColumnId(chrt);
        var dt_check = score_chart.getDataTable().getNumberOfColumns();
        alert(dt);

        \\ alert(dt_check) returns proper number of columns
    });

Problem:

The column number referred to by chrt is equal to the column number of the view NOT the column number of the underlying dataTable. By this I mean, if the dataTable has 10 columns and the view of the dataTable used by score_chart has only 2 columns chrt will return either 1 or 2 regardless of what columns from the dataTable were used in the view. This is causing getColumnId(...) to return a column different from that which I would like.

Any advice would be a great help. Thanks

Upvotes: 0

Views: 174

Answers (1)

asgallant
asgallant

Reputation: 26340

Assuming your view is specified in the ChartWrapper's view parameter, you need to reference the view.columns array to get the column index reference to the underlying DataTable. Also, since the select event fires when users deselect an element, it is possible that the array of selected elements is empty, which would cause this line to throw an error:

var chrt = score_chart.getChart().getSelection()[0].column;

so you need to test the length of the array (and possibly iterate over all array elements if multi-select is enabled in your chart). The code should look like this:

var score_select = google.visualization.events.addListener(score_chart, 'select', function(){
    var selection = score_chart.getChart().getSelection();
    if (selection.length) {
        var chrt = selection[0].column;
        var dt = score_chart.getDataTable().getColumnId(chrt);
        var dt_check = dt.getNumberOfColumns();

        var view = score_chart.getView();
        var dtColumnIndex = view.columns[chart];

        alert('The selected column is ' + dt.getColumnLabel(dtColumnIndex));
    }
});

This assumes that view.columns contains just column references - if it contains calculated columns, you have to decide what you want to do with those.

Upvotes: 1

Related Questions