How to compute the centroid of a polygon in Python
12,203
Solution 1
The polygons are described using WKT.
Using Python? Use Shapely.
from shapely import wkt
p1 = wkt.loads("POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,
-171368.44 5388076.82,-171368.89 5388067.46,
-171379.35 5388068.23))")
p2 = wkt.loads("POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,
-171378.95 5374239.82,-171365.69 5374243.03,
-171364.16 5374237.14,-171365.92 5374236.76,
-171364.26 5374230.26,-171362.67 5374230.63,
-171360.11 5374220.19,-171376.6 5374216.13,
-171379.3 5374226.42))")
print(p1.centroid.wkt) # POINT (-171373.8710815240337979 5388072.5175872016698122)
print(p2.centroid.wkt) # POINT (-171370.4190352254081517 5374229.0108996396884322)
Solution 2
You can use PostGIS functionality or for example the python lib shapely to realize it.
Author by
Admin
Updated on June 14, 2022Comments
-
Admin almost 2 years
I am wondering if there any algorithm where I can compute the center of a polygon in OSM because I've found that each polygon has a different parameters expression:
"POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,-171368.44 5388076.82,-171368.89 5388067.46,-171379.35 5388068.23))" "POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,-171378.95 5374239.82,-171365.69 5374243.03,-171364.16 5374237.14,-171365.92 5374236.76,-171364.26 5374230.26,-171362.67 5374230.63,-171360.11 5374220.19,-171376.6 5374216.13,-171379.3 5374226.42))"
In this expression each one has a different number of parameters so how can i compute the centroid of it?
I am using the postgis to get the polygon information from the spatial information.