Skip to content

Instantly share code, notes, and snippets.

@amercader
Created December 12, 2025 10:22
Show Gist options
  • Select an option

  • Save amercader/eb8d623dadec13eefdf09a29b4fae900 to your computer and use it in GitHub Desktop.

Select an option

Save amercader/eb8d623dadec13eefdf09a29b4fae900 to your computer and use it in GitHub Desktop.
Point in Polygon
def point_in_polygon(point, polygon):
"""
Point in Polygon algorithm adapted from https://stackoverflow.com/questions/217578,
original source: https://wrfranklin.org/Research/Short_Notes/pnpoly.html
:param point: the point to check as an iterable of x,y coordinates (e.g. (x, y))
:param polygon: the polygon to check against, defined as a list of points (e.g. [(x1, y1), (x2, y2)])
:returns: True or False depending on whether the point is contained
"""
point_x, point_y = point
if point in polygon:
return True
min_x = max_x = polygon[0][0]
min_y = max_y = polygon[0][1]
for vertex in polygon:
vertex_x, vertex_y = vertex
min_x = min(vertex_x, min_x)
max_x = max(vertex_x, max_x)
min_y = min(vertex_y, min_y)
max_y = max(vertex_y, max_y)
if point_x < min_x or point_x > max_x or point_y < min_y or point_y > max_y:
return False
contained = False
for i in range(0, len(polygon)):
j = i + 1
if j > len(polygon) - 1:
break
vertex1_x, vertex1_y = polygon[i]
vertex2_x, vertex2_y = polygon[j]
if (vertex1_y > point_y) != (vertex2_y > point_y) and point_x < (
vertex2_x - vertex1_x
) * (point_y - vertex1_y) / (vertex2_y - vertex1_y) + vertex1_x:
contained = not contained
return contained
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment