将图表类型参数作为google图表函数

时间:2016-01-06 12:18:26

标签: javascript php google-visualization

目前我正在使用谷歌图表创建图表。为此,我创建了一个名为myJchart的自定义函数,如下所示。

    function myJChart(ChartPackage,ChartType,ChartData,ChartTitel,ChartSubtitle,Chart3D,ChartHeight,ChartWidth,ChartDivID){

        google.load("visualization", "1", {packages:[ChartPackage]});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable(ChartData);
            var options = {
                title: ChartTitel,
                subtitle: ChartSubtitle,
                is3D: true,
                height: ChartHeight,
                width: ChartWidth               
                };


        var chart = new google.visualization.PieChart(document.getElementById(ChartDivID));
            chart.draw(data, options);
      }

    }

和调用功能

myJChart('corechart','PieChart',<?php echo $jsonTable;?>,'test','test again',true,'600','800','chart_div'); 

以上这个功能运作良好。 现在的问题是,当我将 ChartType 参数传递给谷歌 google.visualization.ChartType 时 我收到以下错误消息

Uncaught TypeError: google.visualization.ChartType is not a function

我使用 [ChartType] ,但我收到此错误Unexpected token [ 任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用ChartWrapper Class来...

主要是因为您只想拨打google.load一次。

ChartWrapper将根据图表类型动态加载所需内容。

&#13;
&#13;
google.load("visualization", "1.1", {packages:["controls"]});
google.setOnLoadCallback(googleLoaded);

// test data
var rowData1 = [['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua  Guinea','Rwanda', 'Average'],
                ['2004/05', 165, 938, 522, 998, 450, 114.6],
                ['2005/06', 135, 1120, 599, 1268, 288, 382],
                ['2006/07', 157, 1167, 587, 807, 397, 623],
                ['2007/08', 139, 1110, 615, 968, 215, 409.4],
                ['2008/09', 136, 691, 629, 1026, 366, 569.6]];

function googleLoaded() {
    myJChart('corechart', 'BarChart', rowData1, 'test', 'test again', true, 600, 800, 'chart_div');
}

function myJChart(ChartPackage, ChartType, ChartData, ChartTitel, ChartSubtitle, Chart3D, ChartHeight, ChartWidth, ChartDivID){
    chart = new google.visualization.ChartWrapper({
        chartType: ChartType,
        containerId: ChartDivID,
        dataTable: google.visualization.arrayToDataTable(ChartData),
        options: {
            title: ChartTitel,
            subtitle: ChartSubtitle,
            is3D: Chart3D,
            height: ChartHeight,
            width: ChartWidth
        }
    });

    chart.draw();
}
&#13;
<script src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
&#13;
&#13;
&#13;