I am trying to use the field calculator in a Python script. I use a formula to calculate shortest distance between two polygons (layer_A
, layer_B
).
The formula for the field calculator works well when used directly on layer_A in QGIS. The formula is:
length(
shortest_line(
$geometry,
geometry(get_feature('layer_B','fieldname',attribute('fieldname')))
)
)
The thing is I can’t figure out how to address the second layer_B
in my Python script. I tried using a string to the file path like that:
fomular = '\'length(shortest_line($geometry,geometry(get_feature(\'' + 'path/to/layer_B' + '\',\"fieldname\",attribute(\'fieldname\')))))\''
The formula generates a new field in layer_A
, but no distance is calculated. Also, Python gives no error. layer_B
seems not to be addressed correctly. What am I doing wrong?
1 Answer 1
Your formula will work if you first make a QgsVectorLayer from the path and add the layers to the canvas. They can be removed immediately after the calculation for clean-up if needs be:
p = QgsProject.instance()
layer_A = QgsVectorLayer('path/to/layer_A', 'layer_A') # the second argument is the layer name
layer_B = QgsVectorLayer('path/to/layer_B', 'layer_B') # the second argument is the layer name
# add layers to canvas
p.addMapLayer(layer_A)
p.addMapLayer(layer_B)
formular = "length(shortest_line($geometry, geometry(get_feature('layer_B', 'fieldname',attribute('fieldname')))))"
calculated = processing.run("native:fieldcalculator", {'INPUT':layer_A, 'FIELD_NAME':'distance', 'FIELD_TYPE':0, 'FIELD_LENGTH':0, 'FIELD_PRECISION':0, 'FORMULA': formular, 'OUTPUT':'TEMPORARY_OUTPUT'})['OUTPUT']
p.addMapLayer(calculated)
# clean-up
p.removeMapLayer(layer_A)
p.removeMapLayer(layer_B)
-
Hello, thanks for the suggested solution, I did everything as described but still get an empty "distance" column. Don’t not what I’m doing wrong.Miron– Miron2022年03月14日 14:12:16 +00:00Commented Mar 14, 2022 at 14:12
-
I have updated my answer. It appears the layers must be present in the map canvas for the calculation to work.Matt– Matt2022年03月21日 14:21:29 +00:00Commented Mar 21, 2022 at 14:21