I'm using "Time data with irregular intervals" chart of Highcharts. As you know when mouse moves over points of line the formatter function runs and shows some information. I want to know index of the point that mouse moves over it. So if mouse moves over first point of the line, tooltip shows "1" and the second point shows "2" and so on. thnx.
8 Answers
One way is to pre-process the data to contain a property with the index. In the Snow-depth example you could do a preparation like this:
function prepare(dataArray) {
return dataArray.map(function (item, index) {
return {x: item[0], y: item[1], myIndex: index};
});
};
to convert the array of [x, y]
to be an object like { x: x, y: y, myIndex: i}
. Then its easy to pick up that index in the formatter with:
formatter: function() {
return 'point ' + this.point.myIndex;
}
Example on jsfiddle
Since the data is sorted you can use a binary search.
A binary search should perform well even for large number of points (from the wikipedia article: "For example, to search a list of one million items takes as many as one million iterations with linear search, but never more than twenty iterations with binary search."
Example:
var bsComparator = function(a, b) {
if (a.x < b.x) { return -1; }
if (a.x > b.x) { return 1; }
return 0;
};
var binarySearch = function(series_data, point) {
var low = 0, high = series_data.length - 1,
i, comparison;
while (low <= high) {
i = Math.floor((low + high) / 2);
comparison = bsComparator(series_data[i], point);
if (comparison < 0) { low = i + 1; continue; }
if (comparison > 0) { high = i - 1; continue; }
return i;
}
return null;
};
tooltip: {
formatter: function() {
var pointIndex = binarySearch(this.series.data, this.point);
return "Point index: " + pointIndex;
}
}
(the binarySearch function above is inspired by http://www.dweebd.com/javascript/binary-search-an-array-in-javascript/)
This is about as hacky as it comes, and will get slow as hell with alot of points, but it'll work. The general idea is to look through all the points in the series' data until you find the one matching the current point:
tooltip: {
formatter: function() {
for(var i=0;i<this.series.data.length;i++){
var item = this.series.data[i];
if(item.x == this.x && item.y == this.y)
return 'point ' + i;
}
return 'not found'
}
}
Live example: http://jsfiddle.net/Fuv4h/