Search code examples
pythonpolygonpointshapefile

Find enclosing ploygon for point in Python, using shapefile


I have a shapefile with a series of polygons which represent counties. I would like to know of a function/module in Python which can derive the 'bounding' polygon given the coordinates of a single point.

In other words, a function which uses a lat/lon coordinate of a point and the shapefile, and returns the polygon within this shapefile which encompasses the point. See diagram:

enter image description here

As you can see, the point is within the 'blue' polygon and this is what I need for any given point.

I understand that there may not be a built-in function to do this but any advice of how to go about this would be excellent, thanks!


Solution

  • The answer from Richard on a similar question is the best.

    Found here: https://stackoverflow.com/a/13433127/7019148

    Copied below for future reference:

    #!/usr/bin/python
    import ogr
    from IPython import embed
    import sys
    
    drv = ogr.GetDriverByName('ESRI Shapefile') #We will load a shape file
    ds_in = drv.Open("MN.shp")    #Get the contents of the shape file
    lyr_in = ds_in.GetLayer(0)    #Get the shape file's first layer
    
    #Put the title of the field you are interested in here
    idx_reg = lyr_in.GetLayerDefn().GetFieldIndex("P_Loc_Nm")
    
    #If the latitude/longitude we're going to use is not in the projection
    #of the shapefile, then we will get erroneous results.
    #The following assumes that the latitude longitude is in WGS84
    #This is identified by the number "4326", as in "EPSG:4326"
    #We will create a transformation between this and the shapefile's
    #project, whatever it may be
    geo_ref = lyr_in.GetSpatialRef()
    point_ref=ogr.osr.SpatialReference()
    point_ref.ImportFromEPSG(4326)
    ctran=ogr.osr.CoordinateTransformation(point_ref,geo_ref)
    
    def check(lon, lat):
        #Transform incoming longitude/latitude to the shapefile's projection
        [lon,lat,z]=ctran.TransformPoint(lon,lat)
    
        #Create a point
        pt = ogr.Geometry(ogr.wkbPoint)
        pt.SetPoint_2D(0, lon, lat)
    
        #Set up a spatial filter such that the only features we see when we
        #loop through "lyr_in" are those which overlap the point defined above
        lyr_in.SetSpatialFilter(pt)
    
        #Loop through the overlapped features and display the field of interest
        for feat_in in lyr_in:
            print lon, lat, feat_in.GetFieldAsString(idx_reg)
    
    #Take command-line input and do all this
    check(float(sys.argv[1]),float(sys.argv[2]))
    #check(-95,47)