This feels like something that should already have a function to do easily, but I can't find one.
What I'm ultimately trying to do: I have a shapefile with 3 features that show bounding boxes; I want to use one of those features to select all the features within it in another shapefile or polygons. I have this running using ogr2ogr, using the -clipsrc and -clipsrcwhere flags to select my bounding box from my bounding box shapefile. This works great, but I cannot include or disclude polygons that fall along the border, and I do not want them clipped. So, I figured I'd use the -spat flag instead and just import the bounding box polygon extent.
I know I can get the extent of my polygon with:
polygon = 'mouth'
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataSource = inDriver.Open(extent_shpfile, 1)
inLayer = inDataSource.GetLayer()
select = "name = '" + polygon + "'"
inLayer.SetAttributeFilter(select)
for feature in inLayer: #inLayer is always of size one because polygon is a unique value
geom=feature.GetGeometryRef()
From here I can parse out the values of geom to get the min and max x and y values. Is there not an ogr call to do this already (like inLayer.GetFeatureExtent() or inLayer.GetExtent(feature_fid)? The latter simply returns the layer extent, and the former doesn't exist, but having to parse it from the feature geometry feels clunky.
Turns out there IS a built in function to do this, my 4 hours of searching (prior to the original post) just failed to bring it to light until I switched to working on something else and stumbled across it accidentally.
extent = geom.GetEnvelope()
Hopefully this post will save someone else the headache of trying to find this function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With