如何从python控制台绘制多边形?


14

我一直在访问和重新访问PyQGIS Cookbook中有关几何处理的页面:http ://documentation.qgis.org/2.0/en/docs/pyqgis_developer_cookbook/geometry.html,但似乎无法弄清楚如何获取从Python控制台绘制的多边形。有人可以帮忙吗?

Answers:


26

它是不是真的复杂,看看内存提供商载体

  • 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

非常感谢您提供的代码。我想知道运行代码后如何摆脱CRS选择对话框?
wannik 2014年

如何添加样式?
cjahangir

3

只需在图层定义中选择CRS: QgsVectorLayer('Polygon?crs=epsg:2154', 'poly' , "memory")例如(此处EPSG 2154用于Lambert 93投影,这是法国大都会的标准设置,但是您可以随意放置)


如何添加样式?
cjahangir
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.