I am trying to save the result of a distance matrix on two layers in CSV (or in shapefile could be okay as well)
You will find the code used for the distance matrix on below:
sLayerName = "Centroids_site"
tLayerName = "Centroids_lotiss"
sLayers = QgsProject.instance().mapLayersByName(sLayerName)
sLayer = sLayers[0]
# Distance between all features from two different layers
tLayers = QgsProject.instance().mapLayersByName(tLayerName)
tLayer = tLayers[0]
sFeats = sLayer.getFeatures()
print(sLayer.featureCount())
for sfeat in sFeats:
sgeom = sfeat.geometry()
tFeats = tLayer.getFeatures()
for tfeat in tFeats:
tgeom = tfeat.geometry()
dist_pl = sgeom.distance(tgeom)
print(sfeat.id(), tfeat.id(), dist_pl)
print(sfeat.id(), 'done')
I have the output on console, but I would like to have it in a file (CSV, preferentially)
The code for the distance matrix come from "OpenSourceOptions" https://opensourceoptions.com/blog/pyqgis-measure-the-distance-between-geometries/
-
3realpython.com/python-csv/#writing-csv-files-with-csvBen W– Ben W2022年06月26日 22:40:12 +00:00Commented Jun 26, 2022 at 22:40
-
3From gis.stackexchange.com/questions/373784/… QgsVectorFileWriter.writeAsVectorFormat(your_layer, Your_path_and_filename, "utf-8", driverName = "CSV" , layerOptions = ['GEOMETRY=AS_XYZ'])M Dollinger– M Dollinger2022年06月27日 05:38:34 +00:00Commented Jun 27, 2022 at 5:38
1 Answer 1
Thanks to the code given by @MDollinger & @BenW I have succeeded to save the output in csv, but first I had to create a virtual layer (see: https://gis.stackexchange.com/a/437794/172081). The final code become:
sLayerName = "Centroids_site"
tLayerName = "Centroids_lotiss"
sLayer = QgsProject.instance().mapLayersByName(sLayerName)[0]
tLayer = QgsProject.instance().mapLayersByName(tLayerName)[0]
# make new memory layer
dist_layer = QgsVectorLayer("None?field=sid:integer&field=tid:integer&field=dist:double", "dist", "memory")
dist_layer.startEditing()
for sfeat in sLayer.getFeatures():
sgeom = sfeat.geometry()
for tfeat in tLayer.getFeatures():
dist_pl = sfeat.geometry().distance(tfeat.geometry())
# make new feature
feat = QgsFeature(dist_layer.fields())
feat["sid"] = sfeat.id()
feat["tid"] = tfeat.id()
feat["dist"] = dist_pl
# add the feature to the table
dist_layer.addFeature(feat)
dist_layer.commitChanges()
QgsProject.instance().addMapLayer(dist_layer)
QgsVectorFileWriter.writeAsVectorFormat(dist_layer, "/Users/Me/Downloads/dist.csv", "utf-8", driverName = "CSV" , layerOptions = ['GEOMETRY=AS_XYZ'])