Snap point to a line

2020-02-29 18:54发布

问题:

I have two GPS coordinates which link together to make a line. I also have a GPS point which is near to, but never exactly on, the line. My question is, how do I find the nearest point along the line to the given point?

回答1:

Game Dev has an answer to this, it is in C++ but it should be easy to port over. Which CarlG has kindly done (hopefully he does not mind me reposting):

public static Point2D nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py,
        boolean clampToSegment, Point2D dest) {
    // Thanks StackOverflow!
    // https://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
    if (dest == null) {
        dest = new Point2D.Double();
    }

    double apx = px - ax;
    double apy = py - ay;
    double abx = bx - ax;
    double aby = by - ay;

    double ab2 = abx * abx + aby * aby;
    double ap_ab = apx * abx + apy * aby;
    double t = ap_ab / ab2;
    if (clampToSegment) {
        if (t < 0) {
            t = 0;
        } else if (t > 1) {
            t = 1;
        }
    }
    dest.setLocation(ax + abx * t, ay + aby * t);
    return dest;
}


回答2:

Try this:

ratio = (((x1-x0)^2+(y1-y0)^2)*((x2-x1)^2 + (y2-y1)^2) - ((x2-x1)(y1-y0) - (x1-x0)(y2-y1))^2)^0.5
        -----------------------------------------------------------------------------------------
                                            ((x2-x1)^2 + (y2-y1)^2)

xc = x1 + (x2-x1)*ratio;
yc = y1 + (y2-y1)*ratio;

Where:
    x1,y1 = point#1 on the line
    x2,y2 = point#2 on the line
    x0,y0 = Another point near the line
    xc,yx = The nearest point of x0,y0 on the line
    ratio = is the ratio of distance of x1,y1 to xc,yc and distance of x1,y1 to x2,y2
    ^2    = square
    ^0.5  = square root

The formular is derived after we find the distant from point x0,y0 to line (x1,y1 -> x2,y3). See here

I've test this code here (this particular one I gave you above) but I've used it similar method years ago and it work so you may try.



回答3:

You can use JTS for that.

  • Create a LineSegment (your line)
  • Create a Coordinate (the point you want to snap to the line)
  • Get Point on the line by using the closestPoint method

Very simple code example:

// create Line: P1(0,0) - P2(0,10)
LineSegment ls = new LineSegment(0, 0, 0, 10);
// create Point: P3(5,5)
Coordinate c = new Coordinate(5, 5);
// create snapped Point: P4(0,5)
Coordinate snappedPoint = ls.closestPoint(c);


标签: java line point