重绘谷歌图表

时间:2014-01-31 14:20:54

标签: javascript google-visualization

大家好我正在使用谷歌图表开发一个Web应用程序。 我想在每次用户选择时重绘图表 这是我的代码

    //Loading google api
    google.load("visualization", "1", {
        packages: ["corechart"]
    });
    google.setOnLoadCallback(drawAllCharts);      
    function drawAllCharts() {
        //Sending server a request
        $.post("index.php", {
            type: "result"
        }, function (data, status) {
            handleResponse(data, true)
        });
    }
    //This function handles response of server which is a JSON string 
    function handleResponse(jsonString, init) {
        //Parsing JSON string into object

        var obj = JSON.parse(jsonString);
        var arrayData = objToStrin(obj); //Converting obj to array
        console.log(arrayData);
        drawDistChart(arrayData, init);
    }
    //This function draws first chart
    function drawDistChart(arrayData, init) {
        //Preparing data
        var dataDistribution = new google.visualization.DataTable();
        dataDistribution.addColumn('string', "Fitness");
        dataDistribution.addColumn('number', "Physical");
        dataDistribution.addColumn('number', "Emotional");
        dataDistribution.addRows(arrayData);
        //Setting few properties 
        var options = {
            title: 'No of People',
            backgroundColor: {
                fill: 'transparent'
            },
            hAxis: {
                title: 'Wellness Score',
                slantedText: true,
                titleTextStyle: {
                    color: 'red'
                }
            }
        };
        //Drawing the chart
   var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(dataDistribution, options);            
}

但没有任何反应,请帮忙

2 个答案:

答案 0 :(得分:0)

您需要添加“select”事件侦听器来处理用户选择图表元素:

google.visualization.events.addListener(chart, 'select', function () {
    var selection = chart.getSelection();
    if (selection.length) {
        // the user clicked on a chart element
        // get row/column information from selection[n].row/column
        // do something with the selection

        // redraw the chart
        chart.draw(dataDistribution, options);
    }
});

答案 1 :(得分:0)

无需每次声明new google.visualization.ColumnChart

只需chart.draw(dataDistribution, options);即可正常工作。

chart.draw(dataDistribution, options);中添加function handleResponse