Google Charts - How to append text to default tool

2019-02-19 09:52发布

I want to add a custom tooltip to my charts by using the default one and for example just append some text to it.

Is this even possible, or to i have to create it all by myself with html?

data= google.visualization.arrayToDataTable([
        ["Element", "Duration ", { role: "style" }, { role: 'tooltip' }],
        ["Count", 23515, "orange", ???],
      ]);   

How it is (Default Tooltip):

enter image description here

How i want it:

Append the duration as readable time, but still keep the default tooltip

enter image description here

1条回答
霸刀☆藐视天下
2楼-- · 2019-02-19 10:21

it's not possible to add content to the default tooltip via standard functionality

to do so requires manipulating the tooltip directly when it is shown

the following working snippet listens for the 'onmouseover' event on the chart
then modifies the tooltip (if found)
using the row # passed as a property of the event argument

keep in mind, the style (font-size) will change according to the size of the chart
the snippet copies the style from the existing lines

google.charts.load('current', {
  callback: function () {
    var dataTable = new google.visualization.DataTable({
      cols: [
        {label: 'Element', type: 'string'},
        {label: 'Duration', type: 'number'},
        {role: 'style', type: 'string'}
      ],
      rows: [
        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 3116, f: '3,116 s'}, {v: 'orange'}]},
        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 8523, f: '8,523 s'}, {v: 'cyan'}]}
      ]
    });

    var options = {
      backgroundColor: 'transparent',
      legend: 'none',
      theme: 'maximized',
      hAxis: {
        textPosition: 'none'
      },
      tooltip: {
        isHtml: true
      }
    };

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.ColumnChart(container);

    google.visualization.events.addListener(chart, 'onmouseover', function (props) {
      var duration = dataTable.getValue(props.row, 1);
      var hours = parseInt( duration / 3600 ) % 24;
      var minutes = parseInt( duration / 60 ) % 60;
      var seconds = duration % 60;

      var tooltip = container.getElementsByTagName('ul');
      var tooltipLabel = container.getElementsByTagName('span');
      if (tooltip.length > 0) {
        // increase tooltip height
        tooltip[0].parentNode.style.height = '95px';

        // add new li element
        var newLine = tooltip[0].appendChild(document.createElement('li'));
        newLine.className = 'google-visualization-tooltip-item';

        // add span for label
        var lineLabel = newLine.appendChild(document.createElement('span'));
        lineLabel.style.fontFamily = tooltipLabel[0].style.fontFamily;
        lineLabel.style.fontSize = tooltipLabel[0].style.fontSize;
        lineLabel.style.color = tooltipLabel[0].style.color;
        lineLabel.style.margin = tooltipLabel[0].style.margin;
        lineLabel.style.textDecoration = tooltipLabel[0].style.textDecoration;
        lineLabel.innerHTML = dataTable.getColumnLabel(1) + ': ';

        // add span for value
        var lineValue = newLine.appendChild(document.createElement('span'));
        lineValue.style.fontFamily = tooltipLabel[0].style.fontFamily;
        lineValue.style.fontSize = tooltipLabel[0].style.fontSize;
        lineValue.style.fontWeight = tooltipLabel[0].style.fontWeight;
        lineValue.style.color = tooltipLabel[0].style.color;
        lineValue.style.margin = tooltipLabel[0].style.margin;
        lineValue.style.textDecoration = tooltipLabel[0].style.textDecoration;
        lineValue.innerHTML = hours + 'h ' + minutes + 'm ' + seconds + 's';
      }
    });

    chart.draw(dataTable, options);
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

to add content to the tooltip using standard functionality requires replacing the tooltip altogether

the best result will be using html tooltips

to use html tooltips, two things must be in place

first, need html column property on tooltip column

{role: 'tooltip', type: 'string', p: {html: true}}

next, need tooltip.isHtml: true in the config options

the tooltip can be provided directly in the data,
or add dynamically, as in the following snippet...

google.charts.load('current', {
  callback: function () {
    var dataTable = new google.visualization.DataTable({
      cols: [
        {label: 'Element', type: 'string'},
        {label: 'Duration', type: 'number'},
        {role: 'style', type: 'string'}
      ],
      rows: [
        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 3116, f: '3,116 s'}, {v: 'orange'}]},
        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 8523, f: '8,523 s'}, {v: 'cyan'}]}
      ]
    });

    dataTable.addColumn({role: 'tooltip', type: 'string', p: {html: true}});

    for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
      var duration = dataTable.getValue(i, 1);
      var hours = parseInt( duration / 3600 ) % 24;
      var minutes = parseInt( duration / 60 ) % 60;
      var seconds = duration % 60;

      var tooltip = '<div class="ggl-tooltip"><span>' +
        dataTable.getValue(i, 0) + '</span><div>' +
        dataTable.getColumnLabel(1) + ': <span>' +
        dataTable.getFormattedValue(i, 1) + '</span></div><div>' +
        dataTable.getColumnLabel(1) + ': <span>' +
        hours + 'h ' + minutes + 'm ' + seconds + 's</span></div></div>';

      dataTable.setValue(i, 3, tooltip);
    }

    var options = {
      backgroundColor: 'transparent',
      legend: 'none',
      theme: 'maximized',
      hAxis: {
        textPosition: 'none'
      },
      tooltip: {
        //trigger: 'selection',
        isHtml: true
      }
    };

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.ColumnChart(container);
    chart.draw(dataTable, options);
  },
  packages:['corechart']
});
.ggl-tooltip {
  border: 1px solid #E0E0E0;
  font-family: Arial, Helvetica;
  font-size: 10pt;
  padding: 12px 12px 12px 12px;
}

.ggl-tooltip div {
  padding-top: 6px;
}

.ggl-tooltip span {
  font-weight: bold;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

查看更多
登录 后发表回答