6

I'm researching the shortest distance between two selected polygons among the number of polygons in a shapefile using PyQGIS. Coding as follows>

layer = iface.activeLayer()

sFeat1 = layer.getFeature(0)
tFeat1 = layer.getFeature(1)

sGeom1 = sFeat1.geometry()
tGeom1 = tFeat1.geometry()

dist_m1 = sGeom1.distance(tGeom1)
print(dist_m1)

The problem is that it always returns the same distance, despite the selected polygon. What is wrong with my code?

2
  • preface: I don't use QGIS or pqgis. But when you think about distance between two polygons, what are you really referring to? From any of the nearest vertexes? An atribtrary spot in the middle of them? There's quite literally an infinite number of distances between any 2 polygons. Perhaps, it would be easier if you extracted the centroids and calculated the distances between those.
    – thus__
    Commented Nov 25, 2022 at 23:54
  • Hi. Is 0 a valid id? Commented Nov 26, 2022 at 0:38

1 Answer 1

10

In your script, you always get the features whose ids are 0 and 1, which are always the same features, not the selected features. Instead, you need to get selected features. Use this script:

layer = iface.activeLayer()

# get selected features list
features = layer.selectedFeatures()

sFeat1 = features[0]
tFeat1 = features[1]

sGeom1 = sFeat1.geometry()
tGeom1 = tFeat1.geometry()
dist_m1 = sGeom1.distance(tGeom1)
print(dist_m1)

Two features must be selected in the active layer for the code to work.

enter image description here

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.