3

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/

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Jun 26, 2022 at 20:33
2

1 Answer 1

2

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'])
answered Aug 9, 2022 at 10:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.