Instantly share code, notes, and snippets.

gka/shape_center.py Created Oct 26, 2011

What would you like to do?
Computes the center of a shapefile multi-polygon
 """ computes the center of a multi-polygon """ def shape_center(shape): """ computes the center of gravity of a shapefile multi-polygon shape must be an instance of shapefile._Shape of the Python Shapefile Library http://packages.python.org/Python%20Shapefile%20Library/ Polygon class comes from here http://pypi.python.org/pypi/Polygon/1.17 """ from Polygon import Polygon parts = shape.parts[:] parts.append(len(shape.points)) # the center computation produces false results for # countries whose shapes cross the 180° longitude # we need to check this far_east = False far_west = False for i in range(len(parts)-1): pts = shape.points[parts[i]:parts[i+1]] if len(pts) == 0: continue if pts[0][0] < -90: far_west = True if pts[0][0] > 90: far_east = True # now we convert the Shape into a Polygon poly = Polygon() for i in range(len(parts)-1): pts = shape.points[parts[i]:parts[i+1]] if far_east and far_west: # correct points if country crosses 180° lon for j in range(len(pts)): if pts[j][0] < 0: pts[j][0] += 360 poly.addContour(pts) # and return its center of gravity return poly.center()