Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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

share|improve this question
    
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 at 0:22

2 Answers 2

up vote 3 down vote accepted

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)
share|improve this answer
    
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 at 15:33

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)
share|improve this answer
    
I've accepted @sgillies answer because no lib dependency but I appreciate also your answer. Thanks –  ThomasG77 Mar 23 at 11:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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