4

I have the given code used to obtain a distance matrix between a source layer (sLayer) and a target layer (tLayer). The output containing sfeat.id(), tfeat.id(), dist_pl is printed in the console but I would like to have that information in a temporary layer. How could I proceed?

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

The code for the distance matrix come from "OpenSourceOptions" https://opensourceoptions.com/blog/pyqgis-measure-the-distance-between-geometries/

1 Answer 1

4

You can use this script:

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

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.