我正在使用Google Timeline chart并希望通过点击城市名称来加载城市的一些细节,但不知道如何做到这一点。
<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/
由于
答案 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>