Calculating the distance between a point and a virtual line of two lat/lngs

Maybe I'm making it too complicated, but what you want is the distance from a point to a line. That is the distance from a point along AB that links AB with C with a line orthogonal to AB. This vector perpendicular to AB is given by

v=[x2-x1, -(y2-y1)] # Point A is [x1,y1] Point B is [x2,y2]

(I have used the square brackets to define a vector, or a two-element array). The distance between C [xp, yp] and point A is

u=[x1-xp, y1-xp]

The distance between the line and C is just the projection of u on to v. If we assume mod(v) = 1 (just normalise it), then

distance = u*v = abs( (x2-x1)*(y1-yp) - (x1-xp)*(y2-y1) )

The only complication is that you probably want to make sure your coordinates are not WGS84 lat/log pairs, but projected (or use geodetic coordinates). You can use OGR or Proj4 for this.


def get_perp( X1, Y1, X2, Y2, X3, Y3):
    """************************************************************************************************ 
    Purpose - X1,Y1,X2,Y2 = Two points representing the ends of the line segment
              X3,Y3 = The offset point 
    'Returns - X4,Y4 = Returns the Point on the line perpendicular to the offset or None if no such
                        point exists
    '************************************************************************************************ """
    XX = X2 - X1 
    YY = Y2 - Y1 
    ShortestLength = ((XX * (X3 - X1)) + (YY * (Y3 - Y1))) / ((XX * XX) + (YY * YY)) 
    X4 = X1 + XX * ShortestLength 
    Y4 = Y1 + YY * ShortestLength
    if X4 < X2 and X4 > X1 and Y4 < Y2 and Y4 > Y1:
        return X4,Y4
    return None

The shortest length is the distance you require, unless I am mistaken?


Being a bit averse to all this math as well, I would come at it from a different angle. I would make it an 'actual' line, rather than a virtual line, and then use existing tools.

If A and B share an attribute, you could connect them by drawing a line (Kosmo GIS has a tool that will create lines from points, and I believe there is also a QGIS plugin for this). Once you have the lines, a 'near' function on the 'C' point layer will give you the distance to the line. Let the software handle the math for you!