# gka / shape_center.py Created October 26, 2011

### SSH clone URL

You can clone with HTTPS or SSH.

Computes the center of a shapefile multi-polygon

View shape_center.py
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 ```""" 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() ```