How to do an Overall Minimum Bounding Rectangle from a Python List of MBRs?

I've converted an ESRI GDB file over to a PostgreSQL DB and went through all the layers now expressed as tables.

I originally looked here but realized that having ~ 49 tables / layers would get hairy: Getting geometry from multiple tables using PostGIS?

Rather than doing the above, I stored the bounding box via ST_Extent for each layer into a Python list.

Is there a way to iterate through the list and get an overall bounding box quick and easy?

If you coordinates are all in the same systems and ready to go, just as simple minimum bounding box algorithm is needed.

Iterate over your list and just find maxX, minX, maxY and minY by comparing each layer at a time. As you check each layer keep the biggest and the smallest value for X and Y by the time you get to the end of the list you should have the values for the MBR for the entire layer set.

Pseudo-Code:

``````# This example we'll have a multi-dimensional array of layer boundaries.
# Index boundaries starting at top and going clock-wise.
layers_boundaries = [[52,86,20,12],[89,85,-12,-1],[25,12,10,8]]
maxX = 0
minX = 0
maxY = 0
minY = 0

for layer in layer_boundaries
if layer[0] > maxX # Check the top boundary of the layer.
maxX = layer[0]
if layer[1] > maxY # Check the right boundary of the layer.
maxY = layer[1]
if layer[2] < minX # Check the bottom boundary of the layer.
minX = layer[2]
if layer[3] < minY # Check the left boundary of the layer.
minY = layer[3]

# By here, we should have the MBR of the layers.
print(maxX, minX, maxY, minY)
``````

As your datasets grow it may be faster to have PostGIS find the boundaries for you. If you have spatial indices turned on and setup, the database should update MBRs every time it needs to and should know the answer to your question already, you just need to spend the time to craft the SQL to query for the MBR for all layers. And if I am not mistaken, if queried about this data often it will 'learn' to index this ahead in its off-time and have this ready, if it doesn't already.

• Thanks. I was hoping there was a function that was already in the PostGIS toolbox. I ended up taking your recommendation and implemented code very similar to what you suggested. Aug 24, 2016 at 18:45