Python – Calculate distance between a point and a line segment in latitude and longitude

latitude-longitudepython

I have a line segments defined with a start and an end point:

A: 
x1 = 10.7196405787775
y1 = 59.9050401935882

B: 
x2 = 10.7109989561813
y2 = 59.9018650448204

where x defines longitude and y defines latitude.

I also have a point:

P:
x0 = 10.6542116666667
y0 = 59.429105

How do I compute the shortest distance between the line segment and the point? I know how to do this in Cartesian coordinates, but not in long/lat coordinates.

Best Answer

Here is an implementation of a formula off Wikipedia:

def distance(p0, p1, p2): # p3 is the point
    x0, y0 = p0
    x1, y1 = p1
    x2, y2 = p2
    nom = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)
    denom = ((y2 - y1)**2 + (x2 - x1) ** 2) ** 0.5
    result = nom / denom
    return result

print distance((0, 0), (3, 4), (5, 6))

# should probably test less obvious cases
assert 1 == distance((0, 0), (1, 1), (2, 1))
# change 0.001 to whatever accuracy you demand on testing.
# Notice that it's never perfect...
assert 0.5 * (2 ** 0.5) - distance((0, 0), (1, 0), (0, 1)) < 0.001