Sunday, 5 June 2016

geometry - How to draw polygons from the python console?


I've been visiting and revisiting the page on geometry handling in the PyQGIS Cookbook: http://documentation.qgis.org/2.0/en/docs/pyqgis_developer_cookbook/geometry.html but can't seem to figure out how to get the polygon to draw from the Python console. Can anyone help?



Answer




it is not realy complicated, look at Memory provider in vector: :



  • a point is created with QgsPoint(x,y) and QgsGeometry.fromPoint(QgsPoint(x,y))

  • a line is created with two points: QgsGeometry.fromPolyline([QgsPoint(x1,y1),QgsPoint(x2,y2)]))

  • a polygon is created with a list of points: QgsGeometry.fromPolygon([[QgsPoint(x1,y1),QgsPoint(x2,y2), QgsPoint(x3,y3)]])


1) two points:


# create a memory layer with two points
layer = QgsVectorLayer('Point', 'points' , "memory")
pr = layer.dataProvider()

# add the first point
pt = QgsFeature()
point1 = QgsPoint(50,50)
pt.setGeometry(QgsGeometry.fromPoint(point1))
pr.addFeatures([pt])
# update extent of the layer
layer.updateExtents()
# add the second point
pt = QgsFeature()
point2 = QgsPoint(100,150)

pt.setGeometry(QgsGeometry.fromPoint(point2))
pr.addFeatures([pt])
# update extent
layer.updateExtents()
# add the layer to the canvas
QgsMapLayerRegistry.instance().addMapLayers([layer])

enter image description here


2) the line connecting the two points


layer =  QgsVectorLayer('LineString', 'line' , "memory")

pr = layer.dataProvider()
line = QgsFeature()
line.setGeometry(QgsGeometry.fromPolyline([point1,point2]))
pr.addFeatures([line])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])

enter image description here


3) a polygon covering the points


layer =  QgsVectorLayer('Polygon', 'poly' , "memory")

pr = layer.dataProvider()
poly = QgsFeature()
points = [point1,QgsPoint(50,150),point2,QgsPoint(100,50)]
# or points = [QgsPoint(50,50),QgsPoint(50,150),QgsPoint(100,150),QgsPoint(100,50)]
poly.setGeometry(QgsGeometry.fromPolygon([points]))
pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])

enter image description here



-


Changes in QGIS 3.0 and onward:


For QGIS 3.0 and onward the above workflow is still correct, but certain functions have changed. See https://qgis.org/api/api_break.html


To update the above code, change following functions:


QgsPoint -> QgsPointXY
QgsfromPoint -> QgsfromPointXY
QgsfromPolyline -> QgsfromPolylineXY
QgsfromPolygon -> QgsfromPolylineXY
QgsfromPolyline -> QgsfromPolylineXY
QgsMapLayerRegistry -> QgsProject

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...