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()
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/


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")


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



QgsVectorFileWriter.writeAsVectorFormat(dist_layer, "/Users/Me/Downloads/dist.csv", "utf-8", driverName = "CSV" , layerOptions = ['GEOMETRY=AS_XYZ'])

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.