7

I was looking in Fiona to get for each feature its extent but I didn't find how.

I have try to far to do something like below

import fiona

with fiona.open('countries/ne_10m_admin_0_countries.shp', 'r') as source:
    for f in source:
        geom = f['geometry']
        print geom

I was expecting to get a method for this at the f variable level. After some documentation reading, I've seen that f is a pure python record. So at the end, how with Fiona can I get the extent (or bounding box) of each feature geometry?

PS: I already know the pure GDAL/OGR python solution so I expect a Fiona solution please

  • I would be really interested in seeing the OGR python solution. I'm going through the documentation, and it looks like extents for layers and features are handled differently in OGR. – midfield99 Apr 16 '14 at 0:22
14

I'd do it like this:

def explode(coords):
    """Explode a GeoJSON geometry's coordinates object and yield coordinate tuples.
    As long as the input is conforming, the type of the geometry doesn't matter."""
    for e in coords:
        if isinstance(e, (float, int, long)):
            yield coords
            break
        else:
            for f in explode(e):
                yield f

def bbox(f):
    x, y = zip(*list(explode(f['geometry']['coordinates'])))
    return min(x), min(y), max(x), max(y)
  • Just in case it's not obvious: the approach above works for deserialized GeoJSON generally and isn't limited to use with Fiona. – sgillies Mar 23 '14 at 15:33
  • I made a slight change to use ESRI's json and this solved one of my problems as well. Thanks! – CMPalmer Apr 3 '16 at 18:40
10

You need to use the function shape of Shapely:

from shapely.geometry import shape
c = fiona.open("ne_10m_admin_0_countries.shp")
# first record
country = c.next()
print "country name :",country['properties']['NAME']
country name : Aruba
# shape(country['geometry']) -> shapely geometry
print "bounds:", shape(country['geometry']).bounds
bounds: (-70.062408006999874, 12.417669989000046, -69.876820441999939, 12.632147528000104)
  • I've accepted @sgillies answer because no lib dependency but I appreciate also your answer. Thanks – ThomasG77 Mar 23 '14 at 11:07
  • It does Thomas, but there you go, it's just not implicit! – Hairy Oct 23 '17 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.