添加Google图表功能到对象

Adding Google Chart function to Objects

本文关键字:对象 功能 Google 添加      更新时间:2023-09-26

我正在尝试将Google Charts功能添加到对象中。我已经在NetBeans中测试了以下代码,它可以给它任意的数据数组:

google.setOnLoadCallback(costChart);
function costChart() {
        var energyType = 'Monthly Cost';
        var energySavings = [1,2,3,4,5,6,7,8,9,10,11,12]; //=this.costSavings
        var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Month');
        data.addColumn('number', energyType + ' Saved');

        data.addRows([
          [month[0], energySavings[0]],
          [month[1], energySavings[1]],
          [month[2], energySavings[2]],
          [month[3], energySavings[3]],
          [month[4], energySavings[4]],
          [month[5], energySavings[5]],
          [month[6], energySavings[6]],
          [month[7], energySavings[7]],
          [month[8], energySavings[8]],
          [month[9], energySavings[9]],
          [month[10], energySavings[10]],
          [month[11], energySavings[11]]
        ]);
        // Set chart options
        var options = {'title': 'Cost Savings',
                       'width':400,
                       'height':300,
                       'hAxis':{format: 'currency'}
                      };
        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.BarChart(document.getElementById('cost_chart_div'));
        chart.draw(data, options);
      }

然而,我想把它放在一个对象中作为一个方法来使用,类似于this. costchart()。它将访问对象内的数据,而不是任意数据,就像注释掉的this。第三行代码中的costSavings。

当我将其设置为对象方法时,我得到错误:"Uncaught ReferenceError: google is not defined"

关于如何正确设置这个方法有什么想法吗?

追问:我添加了一行代码:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
    function run(){
    costChart();
    }

但我仍然得到相同的"谷歌未定义"错误。我试过将脚本添加到部分,但它仍然没有。我已经尝试通过将对象作为参数传递给它来单独调用函数,但仍然是相同的错误。我有一种感觉,这可能是由于我应该包括的方式:

  google.load('visualization', '1.0', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(costChart);

,但我不太确定在哪里/如何在函数中包含这些。它们是在脚本的顶部,还是在调用costChart()的函数中,还是在costChart()函数本身中,等等?

你得到"google is not defined"因为你需要在你的代码的顶部:

  <div id="cost_chart_div"> </div> 
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">
    // Load the Visualization API and the piechart package.
   google.load('visualization', '1.0', {'packages':['corechart']});

一旦你有了这个地方,你应该没有麻烦做你想要的这个。costsavings .