What you want to do is not creating new connections, but creating a path using existing connections/line network. Thus this is a classical routing/network task. In QGIS, under Menu Processing > Toolbox > Network, you find several Shortest path
algorithms for that. There is no algorithm for layer to layer tasks, but you can easily overcome this limitation by using batch mode.
Open Shortest path (layer to point) algorithm and click batch mode.
For End point, click on Autofill... > Add values by Expression and use this expression: aggregate ('end_layer', 'array_agg', $geometry)
Fill in the first row for all other inputs and use Autofill... > Fill down to copy them to the other rows.
In the resulting layers, delete those connections you don't need:, e.g. keep only the lines with attribute A
= 1 and delete those with A
= 2.
For a bit more sophisticated solution, where only the correct connections (start1/end1) are created, see below.
Variant: creating only the correct connections
If you have a lot of different values for your attribtue A
, you don't want to create unnecessary connections that you have to delete afterwards. In this case, with a bit more complex variant, you can only connect start-points 1 with end points 1, start points 2 with end points 2 etc.
Split your start layer with Split Vector Layer algorithm, based on attribute A
and be sure to have a consistent naming of the layers - here I use start_1
, start_2
etc.
Run Shortest path (layer to point) in batch mode as above
To add the vector layers with start points, use Autofill > Add Values by Expression with this expression to load all layers whosw name begin with start
array_filter(
array_foreach(
@map_layers ,
case
when left (layer_property (@element, 'name'),5) = 'start' -- here you define the conditions which layers should be considered: in this case all layers with a name that starts with the 5 characters "start"
then @element
end
), @element is not NULL
)
To add the vector layers with end points, use Autofill... > Calculate by Expression
(attention: this time donf't select Add Values by Expression
!) and insert this expression to get the end point with attribute value (number) corresponding to the number contained in the name of the input layer - so start_1
layer will connect to point feature with attribute A
= 1 etc.:
geometry(
get_feature(
'end', -- layer name
'A', -- attribute name
regexp_matches (layer_property (@START_POINTS, 'name') , '(\\d)')[0]
)
)
The variable @START_POINTS
is created automatically, based on the input you made in the start field.
Result, without showing the initial route/network layer for clarity: