Answers:
它是不是真的复杂,看看内存提供商的载体:
QgsPoint(x,y)
和创建一个点QgsGeometry.fromPoint(QgsPoint(x,y))
QgsGeometry.fromPolyline([QgsPoint(x1,y1),QgsPoint(x2,y2)]))
QgsGeometry.fromPolygon([[QgsPoint(x1,y1),QgsPoint(x2,y2), QgsPoint(x3,y3)]])
1)两点:
# 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])
2)连接两点的线
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])
3)覆盖点的多边形
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])
--
QGIS 3.0及更高版本中的更改:
对于QGIS 3.0及更高版本,上述工作流程仍然正确,但是某些功能已更改。参见https://qgis.org/api/api_break.html
要更新以上代码,请更改以下功能:
QgsPoint -> QgsPointXY
QgsfromPoint -> QgsfromPointXY
QgsfromPolyline -> QgsfromPolylineXY
QgsfromPolygon -> QgsfromPolylineXY
QgsfromPolyline -> QgsfromPolylineXY
QgsMapLayerRegistry -> QgsProject