NVD3 tooltip pointer not updating position after updating chart data - tooltip

I'm using the NVD3 library to draw a graph. I am using the interactive guideline and for some reason after I update the chart data + graph, the tooltip pointers stay at the old position.
When I update the data I do this:
chartData.datum(data).call(chart);
Everything updates fine except the position of the pointers of the tooltip. They seem to get stuck at the old position. I also tried calling this:
chart.update();
I noticed that when resizing my window and calling chart.update(), the pointers are set to the right position.
Someone any idea how to fix this?

Found it! I apparently had to add transition().duration(500);
So in order to update the graph I call this:
chartData.datum(data)
.transition().duration(500)
.call(chart);

Can you post a Little More description about the problem ... Becuase Previously i was having the Same .. that override the nvd3 tooltip function
`this._nvctp = nv.tooltip.calcTooltipPosition;
nv.tooltip.calcTooltipPosition = this.calcTooltipPosition;
calcTooltipPosition : function() {
this.findTotalOffsetTop = function(a, b) {
return 0;
};
this.findTotalOffsetLeft = function(a, b) {
return 0;
};
arguments[0] = [ window.event.pageX, window.event.pageY ];
var p = nvk.tooltip._nvctp.apply(this, arguments);
p.style.left = (window.event.clientX - (p.clientWidth / 2))
+ 'px';
p.style.top = (window.event.clientY - (p.clientHeight * 1.2))
+ 'px';
p.style.opacity = 1;
p.style.position = 'fixed';
return p;
}

Related

Very slow hover interactions in OpenLayers 3 with any browser except Chrome

I have two styles of interactions, one highlights the feature, the second places a tooltop with the feature name. Commenting both out, they're very fast, leave either in, the map application slows in IE and Firefox (but not Chrome).
map.addInteraction(new ol.interaction.Select({
condition: ol.events.condition.pointerMove,
layers: [stationLayer],
style: null // this is actually a style function but even as null it slows
}));
$(map.getViewport()).on('mousemove', function(evt) {
if(!dragging) {
var pixel = map.getEventPixel(evt.originalEvent);
var feature = null;
// this block directly below is the offending function, comment it out and it works fine
map.forEachFeatureAtPixel(pixel, function(f, l) {
if(f.get("type") === "station") {
feature = f;
}
});
// commenting out just below (getting the feature but doing nothing with it, still slow
if(feature) {
target.css("cursor", "pointer");
$("#FeatureTooltip").html(feature.get("name"))
.css({
top: pixel[1]-10,
left: pixel[0]+15
}).show();
} else {
target.css("cursor", "");
$("#FeatureTooltip").hide();
}
}
});
I mean this seems like an issue with OpenLayers-3 but I just wanted to be sure I wasn't overlooking something else here.
Oh yeah, there's roughly 600+ points. Which is a lot, but not unreasonably so I would think. Zooming-in to limit the features in view definitely helps. So I guess this is a # of features issue.
This is a known bug and needs more investigation. You can track progress here: https://github.com/openlayers/ol3/issues/4232.
However, there is one thing you can do to make things faster: return a truthy value from map.forEachFeatureAtPixel to stop checking for features once one was found:
var feature = map.forEachFeatureAtPixel(pixel, function(f) {
if (f.get('type') == 'station') {
return feature;
}
});
i had same issue, solved a problem by setInterval, about this later
1) every mouse move to 1 pixel fires event, and you will have a quee of event till you stop moving, and the quee will run in calback function, and freezes
2) if you have an objects with difficult styles, all element shown in canvas will take time to calculate for if they hit the cursor
resolve:
1. use setInterval
2. check for pixels moved size from preview, if less than N, return
3. for layers where multiple styles, try to simplify them by dividing into multiple ones, and let only one layer by interactive for cursor move
function mouseMove(evt) {
clearTimeout(mm.sheduled);
function squareDist(coord1, coord2) {
var dx = coord1[0] - coord2[0];
var dy = coord1[1] - coord2[1];
return dx * dx + dy * dy;
}
if (mm.isActive === false) {
map.unByKey(mm.listener);
return;
}
//shedules FIFO, last pixel processed after 200msec last process
const elapsed = (performance.now() - mm.finishTime);
const pixel = evt.pixel;
const distance = squareDist(mm.lastP, pixel);
if (distance > 0) {
mm.lastP = pixel;
mm.finishTime = performance.now();
mm.sheduled = setTimeout(function () {
mouseMove(evt);
}, MIN_ELAPSE_MSEC);
return;
} else if (elapsed < MIN_ELAPSE_MSEC || mm.working === true) {
// console.log(`distance = ${distance} and elapsed = ${elapsed} mesc , it never should happen`);
mm.sheduled = setTimeout(function () {
mouseMove(evt);
}, MIN_ELAPSE_MSEC);
return;
}
//while multithreading is not working on browsers, this flag is unusable
mm.working = true;
let t = performance.now();
//region drag map
const vStyle = map.getViewport().style;
vStyle.cursor = 'default';
if (evt.dragging) {
vStyle.cursor = 'grabbing';
}//endregion
else {
//todo replace calback with cursor=wait,cursor=busy
UtGeo.doInCallback(function () {
checkPixel(pixel);
});
}
mm.finishTime = performance.now();
mm.working = false;
console.log('mm finished', performance.now() - t);
}
In addition to #ahocevar's answer, a possible optimization for you is to utilize the select interaction's select event.
It appears that both the select interaction and your mousemove listener are both checking for hits on the same layers, doing double work. The select interaction will trigger select events whenever the set of selected features changes. You could listen to it, and show the popup whenever some feature is selected and hide it when not.
This should reduce the work by half, assuming that forEachFeatureAtPixel is what's hogging the system.

A step value for jqueryUI Resizable?

For other jquery interactions/widgets there are step values.
How might I go about forcing a resize to increase/decrease to certain values?
Must I do something like this?
(side issue, for a more effective hack, how can I know which compass point is being resized?)
var desiredStepPixels = 8;
var containmentLeftPos = 100;
var containmentTopPos = 250;
$("#resizeDivID").resizable({
resize: function( event, ui ) {
var newLeftPxValue = $("#resizeDivID").css("left");
var leftPxModulus = (newLeftPxValue - containmentLeftPos ) % desiredStepPixels;
if ( leftPxModulus != 0){
if (leftPxModulus>(desiredStepPixels/2)){
var forcedNewLeftPx = newLeftPxValue + (desiredStepPixels - leftPxModulus);
$("#resizeDivID").css({"left":forcedNewLeftPx});
}else{
//force a round down on the left side
}
}
//and then etc etc for top, width and height!
}
});
My bad, apologies. Of course Jquery have thought of this!
it's called GRID
http://api.jqueryui.com/resizable/#option-grid
I apologise, I had checked the documentation but just didn=t see what I was looking for!

Redrawing the tooltip inside of the tooltip positioner callback

I'm using the I'm currently using the tooltip formatter function to control the look of the tooltip, including adding some custom css to create an arrow on the side of the tooltip box facing the mouse. I am also using the positioner callback to not only determine the placement of the tooltip, but when it changes from one side of the mouse to the other I'm updating the formatter callback to switch the side of the tooltip the arrow lies on (see code below). Everything works fine, except for the very first point which causes the tooltip to switch sides of the mouse. Its clear that a tooltip's "formatter" function is called before the tooltips "positioner" function ( for reasons that are probably obvious ). However, it prevents me from correctly drawing the tooltip when it changes sides. What I really need to be able to do in the positioner callback is to update the formatter function, and then redraw the tooltip. Is that possible?
positioner: function (boxWidth, boxHeight, point) {
// Set up the variables
var chart = this.chart;
var plotLeft = chart.plotLeft;
var plotTop = chart.plotTop;
var plotWidth = chart.plotWidth;
var plotHeight = chart.plotHeight;
var distance = 40;
var pointX = point.plotX;
var pointY = point.plotY;
// Determine if we need to flip the tooltip from following on the left to
// following on the right
if ((pointX - boxWidth - distance) < plotLeft) {
x = pointX + distance;
chart.tooltip.options.formatter = function () {
// UPATE THE TOOLTIP FORMATTER HERE
};
}
}
Here is a js fiddle example of the issue
http://jsfiddle.net/bteWs/
If you go slowly, and notice the very first point where the switch happens the arrow will be point the wrong direction. After that it corrects ( as described in my post ). Just looking for a solution to get the correct behavior in this case.
You can always have enabled both classes for tooltip, and just remove inproper in positioner, see: http://jsfiddle.net/bteWs/3/
Default formatter:
formatter: function () {
var s = '<div id="custom-tooltip" class="tooltip-left tooltip-right">';
var chart = null;
s += "<div style='padding:5px;color:white'>Some Tooltip</div></div>";
return s;
},
And removing:
if ((pointX - boxWidth - distance) < plotLeft) {
x = pointX + 60;
$("#custom-tooltip").removeClass('tooltip-right');
}
else {
x = Math.max(plotLeft, pointX - boxWidth - 10);
$("#custom-tooltip").removeClass('tooltip-left');
}
I had the same issue. The problem is that positioner is begin called after the formatter. I made a fix to your jsfiddle. It's a huge hack but you can see how you can overcome your problem.
In the fix, I made use of a global. You don't need to but I hacked your fiddle in a hurry. I also got rid of some of your duplicate code.
The trick is to force a refresh on the tooltip after the tooltip switch sides.
positioner: function (boxWidth, boxHeight, point) {
// Set up the variables
var chart = this.chart;
var plotLeft = chart.plotLeft;
var plotTop = chart.plotTop;
var plotWidth = chart.plotWidth;
var plotHeight = chart.plotHeight;
var distance = 40;
var pointX = point.plotX;
var pointY = point.plotY;
var refreshTooltip = false;
var previousAlign = chart.align;
if ((pointX - boxWidth - distance) < plotLeft) {
x = pointX + 60;
chart.align = "left";
}
else {
x = Math.max(plotLeft, pointX - boxWidth - 10);
chart.align = "right";
}
y = Math.min(plotTop + plotHeight - boxHeight, Math.max(plotTop, pointY - boxHeight + plotTop + boxHeight / 2));
if (previousAlign != null && chart.align != previousAlign) {
chart.tooltip.refresh(activePoint);
}
return { x: x, y: y };
}
See the complete fiddle here:
http://jsfiddle.net/anber500/bteWs/1/

JQplot tooltip for multiple y axes

For a JQplot chart with 2 y axes, I am able to set the tooltip but when i hover over a datapoint i need to know to which y axis the tooltip belongs. I need this so that i can display the tooltip after multiplying with the appropriate scale factor. The code i tried is shown below. I thought y will be null when we hover over a data point belonging to y2 axis. But y is never null.
$("#"+sTargetId).bind('jqplotcustomDataMouseOver',
function (ev, seriesIndex, pointIndex, data) {
var chart_left = $("#"+sTargetId).offset().left,
chart_right = ($(window).width() - ($("#"+sTargetId).offset().left + $("#"+sTargetId).outerWidth())),
chart_top = $("#"+sTargetId).offset().top,
x = oPlot.axes.xaxis.u2p(data[0]),
y = oPlot.axes.yaxis.u2p(data[1]),
y2 = oPlot.axes.y2axis.u2p(data[1]);;
if(y===null|| y===undefined){ //this condition doesnt work
var tooltipDataYaxis = data[1]*scaleYaxis1;
var sYDisplay = this.sYAxis1MeasureName;
$('#tooltip').css({left:chart_left+x, top:chart_top+y, marginRight:chart_right});
}
else{
tooltipDataYaxis = data[1]*scaleYaxis2;
sYDisplay = this.sYAxis2MeasureName;
$('#tooltip').css({left:chart_left+x, top:chart_top+y2, marginRight:chart_right});
}
$('#tooltip').html(
'<span style="font-family: Arial;font-size:'+sTooltip+';font:bold;color:#000000;">'+ sYDisplay+': ' + tooltipDataYaxis +'</span>');
$('#tooltip').show();
});
$("#"+sTargetId).bind('jqplotcustomDataUnhighlight',
function (ev, seriesIndex, pointIndex, data) {
$('#tooltip').empty();
$('#tooltip').hide();
});
}
The variable seriesIndex will help to identify which series the tooltip belongs to. :)
I was just playing with jqplot for the first time. quite fun.
In the highlighter plugin jqplot.highlighter.js
I extended it on line 336
elem.html(str + " component:"+neighbor.data[2]);
You might use Chrome developer tools to get the data model at this point and look at the contents of the neighbor object.
(scope variables > Local > neighbor > data )
That's how I did it anywho. Hope it helps.

Changing data in HighCharts series causes y-axis to blow up

I'm seeing some odd behavior in a Highcharts line chart. I have multiple series displayed, and need to let the user change what's called the "Map level" on the chart, which is a straight line across all time periods. Assuming that the correct series is
chart.series[i]
and that the new level that I want it set to is stored in var newMapLevel,
I'm changing that series' data like so:
data = chart.series[i].data;
for(j=0; j<data.length; j++){
data[j].y = newMapLevel;
}
chart.series[i].setData(data);
Calling this function has the desired effect UNLESS the new map level y_value is ONE greater than the highest y_value of all other series, in which case the y-axis scale blows up. In other words, if the y_axis scale is normally from 0 to 275,000, and the highest y_value of any of the other series is, say, 224,000, setting the new map level value to 224,001 causes the y_axis scale to become 0 to 27500M. Yes, that's 27.5 billion.
Might this be a bug in Highcharts? Or is there a better way to change the data in a series?
I've posted a fiddle: http://jsfiddle.net/earachefl/4FuNE/4/
I got my answer from the Highcharts forum:
http://highslide.com/forum/viewtopic.php?f=9&t=13594&p=59888#p59888
This doesn't work as smoothly as I'd like. When you go from 8 as your line to 2 as your line, the scale doesn't adjust back down until you enter another value. Perhaps it's a start in the right direction.
$(document).ready(function(){
$('#clickme').click(function(){
var newMapLevel = $('#newMAP').val();
if(newMapLevel){
for(i=0; i<chart.series.length; i++){
if(chart.series[i].name == 'Map Level'){
data = chart.series[i].data;
for(j=0; j<data.length; j++){
data[j].y = newMapLevel;
}
// get the extremes
var extremes = chart.yAxis[0].getExtremes();
//alert("dataMin: " + extremes.dataMin);
//alert("dataMax: " + extremes.dataMax);
// define a max YAxis value to use when setting the extremes
var myYMax = extremes.dataMax;
if (newMapLevel >= myYMax) {
myYMax = Number(newMapLevel) + 1; // number conversion required
}
if (myYMax > chart.yAxis[0].max) {
alert('cabbbie');
myYMax = chart.yAxis[0].max + 1;
}
//alert("myYMax: " + myYMax);
chart.yAxis[0].setExtremes(extremes.dataMin, myYMax)
// finally, set the line data
chart.series[i].setData(data);
}
}
}
}); });

Resources