Search code examples
pythongisgeospatialgeopandasshapely

Shapely assertion error when checking if a Point object is within a Polygon


I have a dictionary of names of places and associated Polygon geometry.

geom_dict = {'Hanford-Corcoran, CA': 'POLYGON((-119.958925 36.255468, -119.958911 36.254885, -119.958886 36.253897, -119.958853 36.251897, -119.958907 36.249703, -119.958896 36.248311.......))}

I wrote a function to check whether a Point exists in the Polygon and obtain the name of the corresponding place.

def poly_lookup(long, lat, geom_dict):
    # Iterate over dict of market and polygon geom. 
    # Check if the point lies within polygon, if true, get the market. 

    for key, val in geom_dict.items():

        point = Point(long, lat)
        polygon = Polygon(val)
    
        if point.within(polygon):
        
           return key

However, when I call this function I get shapely assertion error.

    File "/Users/", line 169, in
    market = poly_lookup(Lat, Long, geom_dict)
  File "/Users/polygon.py", line 76, in market_Lookup
    polygon = Polygon(val)
  File "/Users/anaconda3/lib/python3.8/site-packages/shapely/geometry/polygon.py", line 243, in __init__
    ret = geos_polygon_from_py(shell, holes)
  File "/Users/kevalshah/opt/anaconda3/lib/python3.8/site-packages/shapely/geometry/polygon.py", line 509, in geos_polygon_from_py
    ret = geos_linearring_from_py(shell)
  File "shapely/speedups/_speedups.pyx", line 343, in shapely.speedups._speedups.geos_linearring_from_py
AssertionError

Solution

  • The error is due to the way your are instanciating your polygon variable. The Polygon constructor doesn't take a wkt string as argument, it expects list of coordinates tuples, more precisely :

    The Polygon constructor takes two positional parameters. The first is an ordered sequence of (x, y[, z]) point tuples and is treated exactly as in the LinearRing case. The second is an optional unordered sequence of ring-like sequences specifying the interior boundaries or “holes” of the feature.

    (source: https://shapely.readthedocs.io/en/stable/manual.html#Polygon)

    To read a wkt string you have to use the shapely.wkt module :

    from shapely import wkt
    

    that you can use like so in your code :

    polygon = wkt.loads(val)
    

    where val contains the wkt string.