Skip to content

Instantly share code, notes, and snippets.

@phobson
Created September 30, 2015 00:11
Show Gist options
  • Save phobson/2d8a5bd2034a16876d4c to your computer and use it in GitHub Desktop.
Save phobson/2d8a5bd2034a16876d4c to your computer and use it in GitHub Desktop.
Silly spatial calc
import math
def point_to_point(point1, point2):
""" Distance between two points
Parameters
----------
point1, point2 : tuples (len = 2) of floats
Tuples of x/y pairs defining each point.
Returns
-------
dist : float
The absolute distance between the points
"""
x1, y1 = point1
x2, y2 = point2
return math.sqrt((y2 - y1)**2 + (x2 - x1)**2)
def point_to_line(linepoint1, linepoint2, point):
""" Shortest distance from line defined by two points
to a third point.
Parameters
----------
linepoint1, linepoint2 : tuples (len = 2) of floats
Tuples of x/y pairs defining each end point of the line.
point : tuple (len = 2) of floats
Third x/y pair defining the point to which the distance
will be determined.
Returns
-------
dist : float
The absolute distance from the line segment to the point
"""
x1, y1 = linepoint1
x2, y2 = linepoint2
xp, yp = point
top = (y2 - y1)*xp - (x2 - x1)*yp + x2*y1 - y2*x1
line_dist = point_to_point(linepoint1, linepoint2)
return math.abs(top) / line_dist
def _prep_pline(polyline):
return polyline, polyline[1:] + polyline[1:]
def point_to_polygon(polygon, point):
polygon1, polygon2 = _prep_pline(polygon)
distances = []
for linepoint1, linepoint2 in zip(polygon1, polygon2):
d = point_to_line(linepoint1, linepoint2, point)
distances.append(d)
index = np.argmin(d)
return distances[index], polygon1[index], polygon2[index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment