Thursday 16 February 2017

Getting list of QgsPoint from polygon Layer in PyQGIS


How do I manage the points in a layer?


from qgis.core import *

def run_script(iface):
layer = QgsVectorLayer(layerType.Polygon+'?'+crs.psg_4326,
'la-florida',

vectorLayerType.memory)

In this moment I need to get all vertex from the polygon which represent the region bound, but I have not find the documentation about how to get it.



Answer



You need objects for QgsGeometry class. In my example (polygon layer with only one feature):


enter image description here


the next code gets the list points of the polygon layer:


layer = iface.activeLayer()

feature = layer.getFeatures().next()


polygon = feature.geometry().asPolygon()

n = len(polygon[0])

for i in range(n):
print polygon[0][i]

After running the code at the Python Console of QGIS, I got each polygon point as a tuple:


(384465,4.45043e+06)

(392424,4.46131e+06)
(409514,4.45616e+06)
(411269,4.44282e+06)
(404480,4.43076e+06)
(392541,4.43486e+06)
(381773,4.44118e+06)
(384465,4.45043e+06)

Observe that the first and last points are matched.


Editing Note:



I edited my answer based in your comment. Next code uses QgsVectorLayer class constructor.


import os
my_path = '/home/zeito/pyqgis_data/polygon8.shp' #this is a Linux path
root,name = os.path.split(my_path)
name = name[:-4]

layer = QgsVectorLayer(my_path,
name,
'ogr') #This is my provider: in your code is memory


QgsMapLayerRegistry.instance().addMapLayer(layer)

feature = layer.getFeatures().next()

polygon = feature.geometry().asPolygon()

n = len(polygon[0])

for i in range(n):
print polygon[0][i]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...