如何在谷歌时间线图表中加载点击事件的一些信息

时间:2016-12-16 08:55:18

标签: javascript jquery html google-visualization

我正在使用Google Timeline chart并希望通过点击城市名称来加载城市的一些细节,但不知道如何做到这一点。

enter image description here

<div id="cityData">

   <!-- city information display hear after ajax success -->

</div>

<div id="timeline" style="height: 180px;"></div>
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var container = document.getElementById('timeline');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();

  dataTable.addColumn({ type: 'string', id: 'President' });
  dataTable.addColumn({ type: 'date', id: 'Start' });
  dataTable.addColumn({ type: 'date', id: 'End' });
  dataTable.addRows([
    [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
    [ 'Adams',      new Date(1797, 2, 4),  new Date(1801, 2, 4) ],
    [ 'Jefferson',  new Date(1801, 2, 4),  new Date(1809, 2, 4) ]]);

  chart.draw(dataTable);
}

小提琴:https://jsfiddle.net/whaqcfnx/

由于

1 个答案:

答案 0 :(得分:0)

您可以为图表生成的text标签添加事件监听器

text元素具有'text-anchor'

的属性

对于行标签

,该属性的值为'end'

只需要等待'ready'事件触发

请参阅以下工作代码段...

google.charts.load('current', {
  packages: ['timeline'],
  callback: function () {
    var container = document.getElementById('timeline');
    var chart = new google.visualization.Timeline(container);
    var dataTable = new google.visualization.DataTable();

    dataTable.addColumn({ type: 'string', id: 'President' });
    dataTable.addColumn({ type: 'date', id: 'Start' });
    dataTable.addColumn({ type: 'date', id: 'End' });
    dataTable.addRows([
      [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
      [ 'Adams',      new Date(1797, 2, 4),  new Date(1801, 2, 4) ],
      [ 'Jefferson',  new Date(1801, 2, 4),  new Date(1809, 2, 4) ]]);

    google.visualization.events.addListener(chart, 'ready', function () {
      var rowLabels = container.getElementsByTagName('text');
      Array.prototype.forEach.call(rowLabels, function (label) {
        if (label.getAttribute('text-anchor') === 'end') {
          label.addEventListener('click', displayDetails, false);
        }
      });
    });

    function displayDetails(sender) {
      document.getElementById('cityData').innerHTML = 'City Data for: ' + sender.target.innerHTML;
    }

    chart.draw(dataTable);
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>
<div id="cityData"></div>