Is this the right way to get centroid x and y of a polygon. How do I get centroid x,y, of a polygon

layerName = "INTERIOR"
layer = QgsMapLayerRegistry.instance().mapLayersByName(layerName)[0]
print layer.name()

for f in layer.getFeatures():
    print f.geometry().centroid().asPoint()
  • 2
    Yes that is fine. Why wouldn't it? – Nathan W Sep 2 '16 at 6:05
  • No i mean that asPoint is use to get centroid of the polygon, polylin and point all can it use it. and this is the only right way? isn't – Muhammad Faizan Khan Sep 2 '16 at 6:11

For similar questions that you are asked in your former posts, I think that you want to know how to visualize them (centroids) at the Map Canvas. In this case you need, e.g., one memory layer. Modifying your code to:

layerName = "INTERIOR"
layer = QgsMapLayerRegistry.instance().mapLayersByName(layerName)[0]
print layer.name()

epsg = layer.crs().postgisSrid()

uri = "Point?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri,

prov = mem_layer.dataProvider()

i= 0

for f in layer.getFeatures():
    feat = QgsFeature()
    pt = f.geometry().centroid().asPoint()
    print pt
    i += 1


After running it at the Python Console of QGIS, with a shapefile with the same name as yours, I got:

enter image description here

Now, they are visible.

| improve this answer | |
  • how can i get the centroid of polygons in qgis3 using python console in it ? – ps1 Sep 17 '18 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.