Skip to content

Instantly share code, notes, and snippets.

@gka
Created October 26, 2011 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gka/1315736 to your computer and use it in GitHub Desktop.
Save gka/1315736 to your computer and use it in GitHub Desktop.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment