Skip to main content
1 of 5
gene
  • 55.4k
  • 3
  • 113
  • 191

it is not complicated:

  • 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)]])

Now, look at Memory provider in vector:

  1. two points:

    create a memory layer with two points

    layer = QgsVectorLayer('Point', 'point' , "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

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

  1. a polygon

    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

-

gene
  • 55.4k
  • 3
  • 113
  • 191