【问题标题】:How to append / add layers to geopackages in PyQGIS如何在 PyQGIS 中向地理包附加/添加图层
【发布时间】:2020-11-26 10:42:46
【问题描述】:

对于一个项目,我正在创建不同的图层,这些图层都应该写入一个地理包中。 我正在使用 QGIS 3.16.1 和 QGIS 中的 Python 控制台,它在 Python 3.7 上运行

我尝试了很多东西,但不知道该怎么做。这是我目前使用的。

vl = QgsVectorLayer("Point", "points1", "memory")
vl2 = QgsVectorLayer("Point", "points2", "memory")

pr = vl.dataProvider()
pr.addAttributes([QgsField("DayID", QVariant.Int), QgsField("distance", QVariant.Double)])
vl.updateFields()

f = QgsFeature()
for x in range(len(tag_temp)):
    f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon[x],lat[x])))
    f.setAttributes([dayID[x], distance[x]])
    pr.addFeature(f)
vl.updateExtents()

# I'll do the same for vl2 but with other data

uri ="D:/Documents/QGIS/test.gpkg"
options = QgsVectorFileWriter.SaveVectorOptions()
context = QgsProject.instance().transformContext()
QgsVectorFileWriter.writeAsVectorFormatV2(vl1,uri,context,options)
QgsVectorFileWriter.writeAsVectorFormatV2(vl2,uri,context,options)

问题是在“test.gpkg”中创建了一个名为“test”的层,而不是“points1”或“points2”。 第二个 QgsVectorFileWriter.writeAsVectorFormatV2() 也覆盖了第一个的输出,而不是将图层附加到现有的地理包中。

我还尝试创建单个 .geopackages,然后使用“Package Layers”处理工具 (processing.run("native:package") 将所有图层合并到一个地理包中,但不幸的是属性类型都转换为字符串.

非常感谢任何帮助。非常感谢。

【问题讨论】:

标签: vector append writer geopackage pyqgis


【解决方案1】:

创建gpkg文件后需要更改SaveVectorOptions,尤其是actionOnExistingFile的模式:

options = QgsVectorFileWriter.SaveVectorOptions()
#options.driverName = "GPKG" 

options.layerName = v1.name()
QgsVectorFileWriter.writeAsVectorFormatV2(v1,uri,context,options)
#switch mode to append layer instead of overwriting the file
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
options.layerName = v2.name()
QgsVectorFileWriter.writeAsVectorFormatV2(v2,uri,context,options)

文档在这里:SaveVectorOptions

我还尝试创建单个 .geopackages,然后使用“Package Layers”处理工具 (processing.run("native:package") 将所有图层合并到一个地理包中,但不幸的是属性类型都转换为字符串.

这是绝对推荐的方式,请考虑报告错误

【讨论】:

  • 感谢您的解决方案,这正是我的项目所需要的
猜你喜欢
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多