谷歌可视化-条形图上的点击事件 isStacked: true [英] google visualization-Click event on barchart isStacked: true

查看:25
本文介绍了谷歌可视化-条形图上的点击事件 isStacked: true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击条形图时,在位于图表顶部的 上显示isStacked: true"条形图的总值.

I'm trying to display the total value of a barchart where 'isStacked: true' on a <span> located on top of the chart when I click on a bar.

我对探索 google.visualization.events.addListener 功能的参考从这里开始.

My reference to explore the capability of google.visualization.events.addListener started here.

当我点击一个栏时,我收到了这个错误:

When I click the a bar I recieved this error:

Uncaught TypeError: Cannot read property 'row' of undefined

或者当我将 row 更改为 column

or when I change the row to column

Uncaught TypeError: Cannot read property 'column' of undefined

任何指针都非常感谢.

这是我的 Django 模板:

Here's my django template:

<script type="text/javascript">   
  $(document).ready(function(){ 
  {% for staff_name, staff_id in params.items %}  
$.ajax({
      url: "{% url user_kpi %}",
      data: { user_stat: {{staff_name}} },
      success: function(responseData) { 
        if (typeof responseData=="object") {                      
          var data = new google.visualization.arrayToDataTable([
            ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
            ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
            ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
            ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
            ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
            ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
            ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
            ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
            ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']]);
          google.setOnLoadCallback(drawVisualization(data, {{staff_name}}));
        }
      }
});
  {% endfor %} 

  });  
  var wrapper;
  function drawVisualization(xdata, id) { 
    // Create and draw the visualization.   
    var visual = 'visualization-'+id.toString();
    //chart = new google.visualization.BarChart(document.getElementById(visual));
    wrapper = new google.visualization.ChartWrapper({
        chartType: 'BarChart',
        dataTable: xdata,
        options: {
                  width:600, height:140,
                  vAxis: {title: null, maxValue: 3500},
                  hAxis: {title: null},

                  animation: {easing: 'in'},
                  axisTitlesPosition: "out",
                  chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
                  focusTarget: "category",
                  fontSize: 12,
                  fontName: "Tahoma",
                  legend: {position: 'none'},
                  series: [{color: 'black', visibleInLegend: false}, {}, {},
                           {color: 'red', visibleInLegend: false}],
                  isStacked: true,
                  backgroundColor: '#eee',
                 },
        containerId: visual
    });
    google.visualization.events.addListener(wrapper, 'ready', function() {
      // grab a few details before redirecting
      google.visualization.events.addListener(wrapper.getChart(), 'select', function() {
        chartObject = wrapper.getChart();
        // checking value upon mousehover
        alert(xdata.getValue(chartObject.getSelection()[0].row, 0));
        //alert(xdata.getValue(chartObject.getSelection()[0].column, 0));
      });
    });

    wrapper.draw();
}   

更新: asgallant 的解释.

Update: As explain by asgallant.

<script type="text/javascript">   
function init () {
{% for staff_name, staff_id in params.items %}
$.ajax({
    url: "{% url user_kpi %}",
    data: { user_stat: {{staff_name}} },
    success: function(responseData) { 
        if (typeof responseData=="object") {                      
            var data = new google.visualization.arrayToDataTable([
                ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
                ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
                ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
                ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
                ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
                ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
                ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
                ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
                ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
            ]);
            drawVisualization(data, {{staff_name}});
        }
    }
});
{% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});

function drawVisualization(xdata, id) { 
  // Create and draw the visualization.   
  var visual = 'visualization-'+id.toString(),
  //chart = new google.visualization.BarChart(document.getElementById(visual));
  wrapper = new google.visualization.ChartWrapper({
      chartType: 'BarChart',
      dataTable: xdata,
      options: {
                width:600, height:140,
                vAxis: {title: null, maxValue: 3500},
                hAxis: {title: null},

                animation: {easing: 'in'},
                axisTitlesPosition: "out",
                chartArea:{left:0,top:0, right:0, width:"100%",height:"100%"},
                focusTarget: "category",
                fontSize: 12,
                fontName: "Tahoma",
                legend: {position: 'none'},
                //orientation: "vertical"
                series: [{color: 'black', visibleInLegend: false}, {}, {},
                         {color: 'red', visibleInLegend: false}],
                isStacked: true,
                backgroundColor: '#eee',
               },
      containerId: visual
  });
  google.visualization.events.addListener(wrapper, 'ready', function() {
    var chart = wrapper.getChart();
    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length) {
            // the user selected a bar
            alert(xdata.getValue(selection[0].row, 0));
            //alert(selection.length);
        }
        else {
            alert('no selection');// the user deselected a bar
        }
    });
  });

  wrapper.draw();
}   

错误:未捕获的错误:无效的行索引未定义.应在 [0-7] 范围内.

Error: Uncaught Error: Invalid row index undefined. Should be in the range [0-7].

由 asgalant 更正把这一行 alert(xdata.getValue(selection.row, 0)); 变成 alert(xdata.getValue(selection[0].row, 0));

推荐答案

首先,你的 AJAX 调用应该在来自 google 加载器的回调中进行,而不是来自文档就绪处理程序(这保证了可视化 API 在以下情况下可用)您尝试使用 API 组件):

First, you AJAX calls should be made inside a callback from the google loader, not from a document ready handler (this guarantees that the the Visualization API is available when you try to use API components):

function init () {
    {% for staff_name, staff_id in params.items %}
    $.ajax({
        url: "{% url user_kpi %}",
        data: { user_stat: {{staff_name}} },
        success: function(responseData) { 
            if (typeof responseData=="object") {                      
                var data = new google.visualization.arrayToDataTable([
                    ['Type', 'Processed Items', { role: 'style' }, 'Processed beyond Due Date', { role: 'style'}],
                    ['PPP', responseData['PPP_ontime'], 'lightgreen', responseData['PPP_due'], 'red'],
                    ['CP', responseData['CP_ontime'], 'gold', responseData['CP_due'], 'red'], 
                    ['RSL', responseData['RSL_ontime'], 'lightblue', responseData['RSL_due'], 'red'],
                    ['MOD', responseData['MOD_ontime'], 'yellow', responseData['MOD_due'], 'red' ], 
                    ['STO', responseData['RECALL_ontime'], 'silver', responseData['RECALL_due'], 'red'],
                    ['TP', responseData['TP_ontime'], 'orange', responseData['TP_due'], 'red'],
                    ['DEMO', responseData['DEMO_ontime'], 'violet', responseData['DEMO_due'], 'red'],
                    ['DUP', responseData['DUP_ontime'], 'brown', responseData['DUP_due'], 'red']
                ]);
                drawVisualization(data, {{staff_name}});
            }
        }
    });
    {% endfor %}
}
google.load('visualization', '1', {packages:['corechart'], callback: init});

然后,在您的 drawVisualization 函数中,您有几个问题:首先,wrapper 是一个全局对象,因此每次调用 wrapper 时它都会被覆盖代码>绘制可视化;这是您问题的主要原因,因为选择"事件针对一个图表触发,但 wrapper 指的是最后绘制的图表,而不是点击的图表(因此,wrapper.getChart().getSelection() 调用返回一个空数组,一个空数组的元素0是undefined,并且undefined没有行或列财产).您需要将包装器本地化为 drawVisualization 函数而不是全局.删除这一行:

Then, in your drawVisualization function, you have a couple of problems: to start with, wrapper is a global object, so it gets overwritten every time you call drawVisualization; this is the primary cause of your issue, as the "select" event fires for one chart, but wrapper refers to the last chart drawn, not the chart clicked on (and thus, the wrapper.getChart().getSelection() call returns an empty array, element 0 of an empty array is undefined, and undefined does not have a row or column property). You need to make wrapper local to the drawVisualization function instead of global. Delete this line:

var wrapper;

并将 var 添加到此行的开头:

and add var to the beginning of this line:

wrapper = new google.visualization.ChartWrapper({

然后你需要调整事件处理程序来测试选择数组的长度,因为用户可以点击一个条形两次,选择然后取消选择条形,导致一个空数组,你会得到相同的错误.事件处理程序需要如下所示:

Then you need to adjust the event handler to test for the length of the selection array, as the user can click a bar twice, which selects and then deselects the bar, resulting in an empty array, and you would get the same error. The event handler needs to look like this:

google.visualization.events.addListener(wrapper, 'ready', function() {
    var chart = wrapper.getChart();
    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length) {
            // the user selected a bar
            alert(xdata.getValue(selection[0].row, 0));
        }
        else {
            // the user deselected a bar
        }
    });
});

这篇关于谷歌可视化-条形图上的点击事件 isStacked: true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆