I am trying to figure out how @AJIKenyon took the expression in this post (QGIS Distance Matrix - with line geometry output?) and used it in Geometry by expression. The layers I have are two projected point data with the following partial attribute table content:

randompts_a enter image description here randompts_b enter image description here

I performed a distance matrix between the two point layers and the partial attribute table of the resulting matrix table is: enter image description here


  1. In using geometry by expression in QGIS 3.22.7, what will be my input layer? Is it the generated distance matrix table or one of the two point layers? enter image description here
  2. Specifically, how do I modify the sample code used in the cited webpage (QGIS Distance Matrix - with line geometry output?)?

1 Answer 1


The starting point is that if you look closely at the provided example, it does not use the Geometry by expression tool but the Geometry Generator in the Style properties of the Matrix layer.

These are slightly different as the latter will natively compute one geometry for each line of the input (Matrix) layer.

Generate the Matrix between points in layers A & B:

enter image description here

This Matrix layer should be a point type layer (that's what the Matrix tool generates), and since it's a layer with Geometry, you can edit it's Symbology to use Geometry Generator.

You should use this formula in the Matrix table Style Style > Marker > Geometry Generator (type line) + the formula:

make_line(geometry(get_feature('random_a_layer_name', 'id', "InputID")), geometry(get_feature('random_b_layer_name', 'id', "TargetID")))

The difference with the provided example is that you have two different layer names for the InputId and the TargetId.

enter image description here

What this does, from the reference post you provided:

In the Matrix table, there is one line per pair of InputId and Target Id (if you have A and B points, it has AxB lines)

What the code does: for each pair, given by the Matrix, it creates a line, between the InputId point of table A and TargetId point of table B.

Note: for the code to work in the 'generate geometry by epression', which would be another approach, you would need to introduce lists that will iterate over all the pairs beween layer A & B. As the Matrix already contains this crossmatch, it's simpler to use it rather than a barebone expression.

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.