Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get feature extent using gdal/ogr

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.

like image 646
Jessica Avatar asked Jul 07 '17 16:07

Jessica


1 Answers

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.

like image 160
Jessica Avatar answered Oct 12 '22 14:10

Jessica