Skip to content

Instantly share code, notes, and snippets.

@fawcett
Last active December 15, 2015 11:39
Show Gist options
  • Save fawcett/5255019 to your computer and use it in GitHub Desktop.
Save fawcett/5255019 to your computer and use it in GitHub Desktop.
A more generic function for point polygon intersects when all that you want are the ID pairs from each intersection. (I am sure that the code could be cleaner or written in a functional style. I am very open to any critiques or improvements, how else am I supposed to learn this stuff....)
import fiona
from shapely.geometry import shape
from rtree import index
def pointInPolyIntersect(pointPath, polyPath, pointIdCol, polyIdCol):
"""
This function runs intersect operations on a pair of point and polygon data sets. No
geometries are returned, just a pair of IDs for each intersection. The ID columns are
specified in the args.
Args: pointPath - string Path to input point feature class.
polyPath - string Path to input polygon feature class.
pointIdCol - string Column that holds the ID to be returned from point feature class.
polyIdCol - string Column that holds the ID to be returned from poly feature calss.
Returns: pntPolyList - list of dictionaries containing a pair of IDs for each
point poly intersection {pointID:polyID}
"""
pointCollect = fiona.open(pointPath,'r')
polyCollect = fiona.open(polyPath,'r')
polyDict = {}
pntPolyList = []
idx = index.Index()
idxCounter = 0
for poly in polyCollect:
idx.add(idxCounter,shape(poly['geometry']).bounds)
polyFeat = shape(poly['geometry'])
polyFeat.polyId = poly['properties'][polyIdCol]
polyFeat.idx = idxCounter
polyDict[idxCounter] = polyFeat
idxCounter += 1
for pnt in pointCollect:
pntFeat = shape(pnt['geometry'])
pntFeat.pntId = pnt['properties'][pointIdCol]
hits = list(idx.intersection((pntFeat.x,pntFeat.y,pntFeat.x,pntFeat.y)))
if len(hits) == 1:
pntPolyList.append(dict([(pntFeat.pntId,polyDict[hits[0]].polyId)]))
elif len(hits) > 1:
for hitIdx in hits:
if polyDict[hitIdx].intersects(pntFeat):
pntPolyList.append(dict([(pntFeat.pntId,polyDict[hitIdx].polyId)]))
return pntPolyList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment