带滑块范围的连续轴图不会画?

时间:2017-05-26 19:53:12

标签: javascript jquery html charts google-visualization

我发现自己在这个网络开发项目中发现自己,并希望有人能帮助我更好地理解为什么我的某个谷歌图表不会在我的页面上绘制。

我有一个工作测试页面,图表绘制了我想要的方式,这是jsfiddle,所以如果你想测试你可以得到确切的代码 http://jsfiddle.net/dlaliberte/pfTqP/

我直接从这个有效的页面中提取代码,并将其放入我的页面中,该页面上已有4个其他正在运行的谷歌图表。现在,当我添加此图表时,它不会给我任何错误,但它不会绘制。

我将发布第一张图表的javascript以及我尝试修复的图表(以' ###'分隔),以及我的页面上它应该绘制的位置,我希望有更多经验的人可以帮助我找出问题的来源,因为经过几个小时的调整和运行它我还不确定出了什么问题。

    //################################### UPDATED JAVASCRIPT ####################################
     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>


         <script src="js/bootstrap.min.js"></script>
         <script src="js/jquery.csv.min.js"></script>

             <script type="text/javascript"> // load the visualisation API

                google.charts.load('visualization', 'current', '1.1', 
                    {
                        callback: drawCharts,
                        packages: ['corechart', 'controls']
                    });


    /* Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawLineChart);
    google.charts.setOnLoadCallback(drawBarChart);
    google.setOnLoadCallback(drawVisualization);
    */
    function drawCharts() {
        drawLineChart();
        drawBarChart();
        drawBarVisualization();
        drawPieVisualization();
        drawVisualization();
    }

    function drawLineChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);
        var options = {
                        title: 'Average Ratings',
            'vAxis': { title: "Average Rating" },
            'width': 1100, 
            'height': 540,
            'legend': { position: 'bottom'},
            'is3D':true,
            'padding': 20,
            'backgroundColor': 'Ivory',
            'color':'Black',
            hAxis: {
                textStyle:{color: 'Black', weight: 'bold'}
                    },
            series: 
            {
            0: { color: 'Black', pointShape: 'square'},
            }


        }
      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

      chart.draw(data, options);


      google.visualization.events.addListener('testBtn', 'click',
      function(event) {
        data.sort({column: 0, desc: false});
        chart.draw(data, options);
      });

      changeLineRange = function() {
          data.sort({column: 0, desc: false});
          chart.draw(data, options);
        };

      changeLineRangeBack = function() {
          data.sort({column: 0, desc: true});
          chart.draw(data, options);
        };


    }


    function drawBarChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

        var options = {
            title: 'Average Ratings',
            'vAxis': { title: "Average Rating" },
            'width': 700, 
            'height': 540,
            'legend':{position:'top',alignment:'start'},
            'is3D':true,
            'padding': 20,
            'backgroundColor': 'Ivory',
            series: {
            0: { color: 'Black' },
          },
          'hAxis': {
                    title: "Date",
                    gridlines: { count: 3, color: '#CCC' },
                    format: 'dd-MMM-yyyy'
                }


        }
      // Instantiate and draw our chart, passing in some options.

      var chart2 = new google.visualization.ColumnChart(document.getElementById('bar_chart_div'));

      chart2.draw(data, options);


      changeOptions = function() {
          chart2.setOption('is3D', true);
          chart2.draw();
        };
    }

$(document).ready(function(){
    $('[data-toggle="popover"]').popover();
});


$('#myTabs a').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})



        //Triple Line Chart

            function drawVisualization() {
               $.get("MockWeek.csv", function(csvString) {
                  // transform the CSV string into a 2-dimensional array
                  var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}, {onParseValue: $.csv.hooks.castToScalar});

                  // this new DataTable object holds all the data
                  var data = new google.visualization.arrayToDataTable(arrayData);
                  // CAPACITY - En-route ATFM delay - YY - CHART
                  var crt_ertdlyYY = new google.visualization.ChartWrapper({
                     chartType: 'LineChart',
                     containerId: 'crt_ertdlyYY',
                     dataTable: data,
                     options:{
                         'title': 'Average Ratings',
                        'vAxis': { title: "Average Rating" },
                        'width': 1100, 
                        'height': 540,
                        'backgroundColor': 'Ivory',
                        'color':'Black',
                        'hAxis': {
                    title: "Date",
                    gridlines: { count: 3, color: '#CCC' },
                    format: 'dd-MMM-yyyy'
                },
                        title: 'KWh Usage - Temperature Projected',
                        titleTextStyle : {color: 'Black', fontSize: 14},
                        curveType: 'function'
                     }
                  });
                  crt_ertdlyYY.draw();




                  changeRange = function() {
          data.sort({column: 0, desc: false});
          crt_ertdlyYY.draw();
        };

            changeRangeBack = function() {
          data.sort({column: 0, desc: true});
          crt_ertdlyYY.draw();
        };
               });
            }
            google.setOnLoadCallback(drawVisualization)




    //Triple Pie Chart

            function drawPieVisualization() {
               $.get("Thornton.M2.csv", function(csvString) {
                  // transform the CSV string into a 2-dimensional array
                  var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}, {onParseValue: $.csv.hooks.castToScalar});


                  // this new DataTable object holds all the data
                  var data = new google.visualization.arrayToDataTable(arrayData);
                  // CAPACITY - En-route ATFM delay - YY - CHART
                  var pieMain = new google.visualization.ChartWrapper({
                     chartType: 'BarChart',
                     containerId: 'pieMain',
                     dataTable: data,
                     options:{
                         title: 'Bar Chart Test',
                        'vAxis': { title: "Bar Chart Test" },
                        'width': 1100, 
                        'height': 530,
                        'backgroundColor': 'Ivory',
                        'color':'Black',
                        'hAxis': {
                    title: "Date",
                    gridlines: { count: 3, color: '#CCC' },
                    format: 'dd-MMM-yyyy'
                },
                        title: 'Bar Chart Test',
                        titleTextStyle : {color: 'Black', fontSize: 16},
                     }
                  });
                  pieMain.draw();
               });
            }
            google.setOnLoadCallback(drawPieVisualization)

            changeRange = function() {
          pieMain.sort({column: 0, desc: false});
          pieMain.draw();
        };

            changeRangeBack = function() {
          pieMain.sort({column: 0, desc: true});
          pieMain.draw();
        };



function drawVisualization() {
  var dashboard = new google.visualization.Dashboard(
       document.getElementById('dashboard'));

   var control = new google.visualization.ControlWrapper({
     'controlType': 'ChartRangeFilter',
     'containerId': 'control',
     'options': {
       // Filter by the date axis.
       'filterColumnIndex': 0,
       'ui': {
         'chartType': 'LineChart',
         'chartOptions': {
           'chartArea': {'width': '90%'},
             'hAxis': {'baselineColor': 'none' }
         },
         // Display a single series that shows the closing value of the stock.
         // Thus, this view has two columns: the date (axis) and the stock value (line series).
         'chartView': {
           'columns': [0, 3]
         },
         // 1 day in milliseconds = 24 * 60 * 60 * 1000 = 86,400,000
         'minRangeSize': 86400000
       }
     },
     // Initial range: 2012-02-09 to 2012-03-20.
     'state': {'range': {'start': new Date(2012, 1, 9), 'end': new Date(2012, 2, 20)}}
   });

   var chart = new google.visualization.ChartWrapper({
     'chartType': 'CandlestickChart',
     'containerId': 'chart',
     'options': {
       // Use the same chart area width as the control for axis alignment.
       'chartArea': {'height': '80%', 'width': '90%'},
       'hAxis': {'slantedText': false},
       'vAxis': {'viewWindow': {'min': 0, 'max': 2000}},
       'legend': {'position': 'none'}
     },
     // Convert the first column from 'date' to 'string'.
     'view': {
       'columns': [
         {
           'calc': function(dataTable, rowIndex) {
             return dataTable.getFormattedValue(rowIndex, 0);
           },
           'type': 'string'
         }, 1, 2, 3, 4]
     }
   });

   var data = new google.visualization.DataTable();
   data.addColumn('date', 'Date');
   data.addColumn('number', 'Stock low');
   data.addColumn('number', 'Stock open');
   data.addColumn('number', 'Stock close');
   data.addColumn('number', 'Stock high');


   // Create random stock values, just like it works in reality.
   var open, close = 300;
   var low, high;
   for (var day = 1; day < 121; ++day) {
     var change = (Math.sin(day / 2.5 + Math.PI) + Math.sin(day / 3) - Math.cos(day * 0.7)) * 150;
     change = change >= 0 ? change + 10 : change - 10;
     open = close;
     close = Math.max(50, open + change);
     low = Math.min(open, close) - (Math.cos(day * 1.7) + 1) * 15;
     low = Math.max(0, low);
     high = Math.max(open, close) + (Math.cos(day * 1.3) + 1) * 15;
     var date = new Date(2012, 0 ,day);
     data.addRow([date, Math.round(low), Math.round(open), Math.round(close), Math.round(high)]);
   }




   dashboard.bind(control, chart);
   dashboard.draw(data);
}


    </script>

这就是我在我的页面上绘制图表的位置,它位于一组4个标签中,因此用户可以在不同的图表中进行选项卡,到目前为止,它的工作方式非常完美。

        <div class="col-md-12">
          <h2 align="center" class="featurette-heading">Current Demand -<span style="color: Ivory;"> Hourly Usage</span></h2>
          <br/>
    <ul class="nav nav-tabs" role="tablist" data-tabs="tabs">
    <li role="presentation" class="active"><a href="#home" class="buttonAnimate" aria-controls="home" role="tab" data-toggle="tab">Usage</a></li>
    <li role="presentation"><a href="#profile" class="buttonAnimate"  aria-controls="profile" role="tab" data-toggle="tab">Demand</a></li>
    <li role="presentation"><a href="#messages" class="buttonAnimate"  aria-controls="messages" role="tab" data-toggle="tab">Daily</a></li>
    <li role="presentation"><a href="#settings" class="buttonAnimate"  aria-controls="settings" role="tab" data-toggle="tab">Monthly</a></li>

  </ul>

    <div class="tab-content">
      <div role="tabpanel" class="tab-pane fade in active" align="center" id="home"> <div class="chart" id="chart_div"></div> 
      <button class="btn btn-primary raised" onclick="changeLineRange();">
                Ascending
              </button>

              <button class="btn btn-primary raised" onclick="changeLineRangeBack();">
                Descending
              </button><br /></div>
      <div role="tabpanel" class="tab-pane fade" align="center" id="profile"><div  class="chart" id="crt_ertdlyYY"></div>

      <button class="btn btn-primary raised" onclick="changeRange();">
                Ascending
              </button>

              <button class="btn btn-primary raised" onclick="changeRangeBack();">
                Descending
              </button><br /></div>


  // ############################## THIS IS THE TAB PANEL WHERE I'M DRAWING THE NEW CHART ############################

      <div role="tabpanel" class="tab-pane fade">
        <div  class="chart" id="dashboard">
            <div id="chart" style='width: 915px; height: 300px;'></div>
            <div id="control" style='width: 915px; height: 50px;'></div>
        </div>
    </div>

      <div role="tabpanel" class="tab-pane fade" id="settings"><div  class="chart" id="pieMain"></div></div>
    </div>



        </div>

我不确定您还需要看到什么,再次我在这里的元素,并试图掌握如何实现这一点,谢谢!

1 个答案:

答案 0 :(得分:1)

这里有几个问题......

首先,代码与旧版和新版谷歌图表混合在一起

旧库使用jsapi加载库

<script src="http://www.google.com/jsapi"></script>

新库使用gstatic

<script src="https://www.gstatic.com/charts/loader.js"></script>

根据release notes ...

  

通过jsapi加载程序保留的Google图表版本不再一致更新。请从现在开始使用新的gstatic加载程序。

接下来,load语句和callback每页只能使用一次

一旦callback触发,您可以根据需要绘制尽可能多的图表

callback也可以直接放在load声明

尝试设置类似以下内容......

google.charts.load('current', {
  callback: drawCharts,
  packages: ['controls', 'corechart']
});

function drawCharts() {
  drawLineChart();
  drawVisualization();
}

function drawLineChart() {
  ...
}

function drawVisualization() {
  ...
}