I have a function that takes latitude and longitude coordinates, and returns information related to the polygon which contains the coordinates. In other words:
def coords_to_info(lat, lng):
#check in which polygon the point lies
return polyName
to check if the point is inside the polygon, I have tried two different functions:
def point_in_poly(x,y,poly):
"""
function to check if a point is in a 2D polygon
"""
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
print point_in_poly(lat, lng, lBoundary)
and
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
coordPoint = Point(lat, lng)
coordPolygon = Polygon(lBoundary)
print coordPolygon.contains(coordPoint)
lBoundary is a list of tuples that is closed (first and last points are equal): [(a,b), (c,d), (e,f), (a,b)]
Both approaches work perfectly for test data and small convex data, but return false for most real data polygons.
I have tested both functions rather extensively with mock data (I tested all these types of polygons ), but when I apply it to most of my real data the functions cease working.
Are there any factors that would affect these functions to give false negatives, such as polygon size, decimal places of coordinates, or other such trivialities?