Created
October 26, 2011 07:58
-
-
Save gka/1315736 to your computer and use it in GitHub Desktop.
Computes the center of a shapefile multi-polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment