Check if point is inside polygon print True or False using Ray Casting

18 views
Skip to first unread message

Basil Tufail

unread,
Oct 4, 2017, 2:51:49 AM10/4/17
to Geospatial Python
i have a code which basically first checks if a point is in a polygon using Ray Casting method and then plots the shapefile. 
what i want  is that the code should only plot the shapefile if the given point lies inside any polygon of the given shapefile.
there is some issue with the first part as it says TRUE even if the point is not inside any polygon of my shapefile

from shapely.geometry import Polygon, Point
import shapefile as shp
import matplotlib.pyplot as plt
polygon = shp.Reader("D:/New folder1/21_8_2016.shp") 
polygon = polygon.shapes()  
shpfilePoints = [ shape.points for shape in polygon ]



polygons = shpfilePoints

for polygon in polygons:
    poly = Polygon(polygon)


lat=15.139078
lon=120.763779

def point_in_poly(x,y,poly):

    n = len(poly)
    inside = True
    
    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(lon,lat,polygon)
 
sf = shp.Reader("D:/New folder1/21_8_2016.shp")
plt.figure()
for shape in sf.shapeRecords():
    x = [i[0] for i in shape.shape.points[:]]
    y = [i[1] for i in shape.shape.points[:]]
    plt.plot(x, y, color = 'blue')
plt.scatter(lon, lat, s=10, c='red', zorder=10)
    
plt.show()

the given lat lon in the code are outside any polygon and the following are inside one of  the polygons 
15.094997
120.836563

Attached is also the shapefile
New folder1.rar
Reply all
Reply to author
Forward
0 new messages