Page 1 of 1

Find the nearest point on Bottom-Axis when clicking chart

Posted: Thu Sep 25, 2014 2:23 pm
by 16568578
Dear all,

I am searching for the easiest way to find the nearest point from a "click" position on the chart.
I am interested only in results from one series (IndexSeries) and only regarding the x position.

In former times this could be established by the NearestTool - unfortunately it is working on all axis now.

Any ideas ?
Thanks in advance for any tip.
Best regards
Christian

Re: Find the nearest point on Bottom-Axis when clicking chart

Posted: Fri Sep 26, 2014 10:12 am
by yeray
Hi Christian,

If you know the series you want to find the nearest XValue to the mouse X position clicked, you can loop the values to search it. Ie:

Code: Select all

uses Series, Math;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Chart1.View3D:=False;

  Chart1.AddSeries(TLineSeries).FillSampleValues();
  Chart1.OnClick:=Chart1OnClick;
end;

procedure TForm1.Chart1OnClick(Sender: TObject);
var clickedXValue: Double;
    clickedXPoint, i, tmpDist, minDist, minDistIndex: Integer;
begin
  clickedXPoint:=Chart1.GetCursorPos.X;
  clickedXValue:=Chart1.Axes.Bottom.CalcPosPoint(clickedXPoint);
  Caption:='clickedXValue: ' + FormatFloat('#0.##', clickedXValue);

  if (Chart1.SeriesCount>0) and (Chart1[0].Count>0) then
  begin
    minDist:=Abs(clickedXPoint-Chart1[0].CalcXPos(0));
    minDistIndex:=0;
    for i:=1 to Chart1[0].Count-1 do
    begin
      tmpDist:=Abs(clickedXPoint-Chart1[0].CalcXPos(i));
      if tmpDist<minDist then
      begin
        minDist:=tmpDist;
        minDistIndex:=i;
      end;
    end;
    Caption:=Caption + ', Nearest Index: ' + IntToStr(minDistIndex) + ', ' +
       'Nearest X Value: ' + FormatFloat('#0.##', Chart1[0].XValue[minDistIndex]);
  end;
end;