(google charts) I want to show linechart Y-value in a tooltip on mouseover?

908 views Asked by At

How could I implement such mouseover effect that whenever mouse is over the linechart it shows every lines Y-value in an tooltip on hovered X?

So, in the end by moving mouse over the chart it should always show a tooltip that is updated constantly with Y value based on changed X? Now it shows tooltip only on X-scales steps e.g. 2010,2011,2012,2013,2014...

1

There are 1 answers

0
nbering On

I don't have time at this very moment to write a complete solution, but I can try to point you in the right direction in terms of the part you will need that is directly related to the Google Charts API.

There Is Not A Simple Solution

First off, I'd like to make it very clear that there is not, to my knowledge, a simply solution built into the Google Charts API for this. Anything you right for this will involve rendering your own tooltip element, positioning it to the mouse location, and filling the tooltip with data yourself.

A JavaScript Framework of your choice will probably help a lot. Most have plugins or modules to handle mouseover and mouse position detection, though I can't recommend any specifically because I haven't tried this.

Chart Layout Interface

What you need to get the data values belonging to the mouse location is the Chart Layout Interface. You can get this as follows:

// create a line chart and set up a variable to store your interface
// on outside the scope of your ready handler, so you can use the
// interface in your mouse event code.
var layoutInterface;
var chart = new google.visualization.LineChart(document.getElementById('container-id'));

// set up a handler for the chart's ready event
// the chart layout interface is not available until the chart has
// been drawn
var readyHandler = function(){
  layoutInterface = chart.getChartLayoutInterface();
};

// register the event handler
google.visualization.events.addListener(chart, 'ready', readyHandler);

I learned this from the demo here.

You will be using the getHAxisValue(xCoordinate) and getVAxisValue(yCoordinate) methods on the layout interface to get the data values corresponding to the x and y coordinates of the chart. The coordinates are relative to the chart's container element. See the Line Chart Documentation for information on methods available on the layout interface.

Mouse Event Handling

The mouse handling part of this is beyond the scope of my knowledge, but I do know that it is possible. I think you need to register a mouse enter event handler on your chart's container element, which would then register a mouse move, and mouse exit on the same element. The mouse exit would set display:none on your tooltip element and de-register the mouse move handler. The mouse move handler would set the absolute position of your tooltip element to the mouse location, and set it's content to the values retrieved from the chart layout interface.

Good Luck!