I am working in Python 3.7 using ogr to check if a point is inside a polygon. Here I put the code. The result in geom is not compatible with the tuple list data type used by the point_inside function.

How can this information be made compatible?

from osgeo import ogr

def point_inside_polygon(x,y,poly):

    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:
                        xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside
file = ogr.Open("C:/Programas/Python/salida.shp/MSK_CLOUDS_B00.shp")
shape = file.GetLayer()
feature = shape.GetFeature(0)
for feature in shape:

 #geom  = feature.GetGeometryRef() 
 geom = feature.geometry()
 print (geom)
 print(point_inside_polygon(-90.2,14.3,geom) )

Why not use the contains methods on the polygon (geom)?

p1 = Point(-90.2, 14.3)

for feature in shape: 
     geom = feature.geometry()

     if geom.contains(p1):
  • It gives me the error: File "C:/Programas/Python/puntodentrodes22.py", line 36, in <module> if geom.contains(p1): AttributeError: 'Geometry' object has no attribute 'contains' – Jose Cordovez Feb 10 at 17:31
  • I'm not sure what returns: feature.geometry () – Jose Cordovez Feb 10 at 17:35


for feature in shape:
 #geom  = feature.GetGeometryRef() 
 geom = feature.geometry()
 json_geom = feature.ExportToJson()

 geom = json.loads(json_geom)
 poly=(geom['geometry'] ['coordinates'])
 print ("------")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.