Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if point is on line in Java Swing

I have drawn a line and then a point, and then I want to check if the point is on the line or not. I have taken a line coordinate in array (as there was more than one line). I want to check the current point in on the last line or not?

if (positionX1 == positionX2 && positionY1 == positionY2) {
    float m = line.getSlope(
        drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    m = Float.parseFloat(df.format(m));
    float c = line.getIntercept(
        drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    c = Math.round(c);
    m1 = line.getSlope(positionX2, positionY2,
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    m1 = Float.parseFloat(df.format(m1));
    System.out.println(m + "   " + m1);
    c1 = line.getIntercept(positionX2, positionY2,
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    c1 = Math.round(c1);

    if (m == m1 && ((c == c1) || (c == c1 - 1) || (c == c1 + 1))) {
        System.out.println("Point is on Line");
    }
}

Problem is when a point is near the starting point of line or when a line is about vertical values of m1 and c1 changes with big difference. So, there's a problem for detecting if a point on line or not. How can I check for this situation?

like image 859
Parth Soni Avatar asked Nov 21 '25 10:11

Parth Soni


1 Answers

Line2D.ptSegDist(x1, y1, x2, y2, xP, yP) returns 0.0 if the point (xP, yP) is on the line segment from (x1, y1) to (x2, y2). Line2D.ptLineDist does the same thing for the infinite line.

like image 60
Louis Wasserman Avatar answered Nov 24 '25 01:11

Louis Wasserman