Skip to content
Create a gist now

Instantly share code, notes, and snippets.

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
Polygon class comes from here
from Polygon import Polygon
parts =[:]
# 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
# and return its center of gravity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.