vector - 如何在 PyQGIS 中向地理包追加/添加图层

标签 vector append writer geopackage pyqgis

对于一个项目,我正在创建不同的图层,这些图层都应该写入一个地理包中。 我正在使用 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() 也会覆盖第一个 QgsVectorFileWriter.writeAsVectorFormatV2() 的输出,而不是将图层 append 到现有的地理包中。

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

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

最佳答案

创建 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

I also tried to create single .geopackages and then use 'Package Layers' processing tool (processing.run("native:package") to merge all layers into one geopackage, but then the attributes types are all converted into strings unfortunately.

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

关于vector - 如何在 PyQGIS 中向地理包追加/添加图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65020423/

相关文章:

vector - 确定点列表是否适合 "formation"?

c++ - vector 中元素的位置

c++ - 将文本文件存储到类中

javascript - 隐藏 ajax append 的 html 直到某个点

haskell - 使用 Maybe 和 Writer 过滤列表并跟踪过滤器命中

c++ - 指针 vector

c++ - 无法将记录 append 到二进制文件

unix - 将命令输出 append 到不带换行符的文件

Python .csv 编写器

python - 我的 CSV 编写器代码在字符之间写入分隔符而不是字符串