3

I would like to know if it is possible to sort a list of line features in the exact order in which they appear on the canvas, given the starting feature. In this case the list of linefeatures represents a connection from point A to point B passing by point C using line features from a layer as the possible route.

I used the points to route script (from here) to generate the new routelayer using a startpoint, endpoint and points to pass by. Unfortunately this generated routelayer does not contain information about underlying line features and their spatial order. For that I used geometry.contains() and geometry.overlaps() functions to get the original features from the underlying line layer. The problem with that is, there is no order to the line features.

The code for that is as follows:

selections=[] 
for f in routelayer.getFeatures():   #iterating over route
    for a in originallayer.getFeatures(): #itering over all existing line features

        if f.geometry().contains(a.geometry()):          
            selections.append( a )

        elif f.geometry().overlaps(a.geometry()):          
            selections.append( a )

Here is a visual example of the problem:

The colored lines represent elements of selected features from the code above. Each feature has an ID as shown in the image. It's important to note that the IDs are not in any logical order, so sorting them doesn't achieve what I need.

enter image description here

My unsorted list looks a follows (example):

ID

4
56
10
8
15

I would like it to be in the correct order of line elements for the route from A to B.

ID

8
4
56
15
10

Anyone got an idea on how to solve this? If there is a way to get the correct order of underlying line features at the stage of generating the route it would also work.

  • I think i did that once by converting the lines into a multiline feature and then back to linestrings. But i can't say if i used shapely or gdal/org python bindings. – Andreas Müller Sep 4 '18 at 18:50
2

Try this workflow:

  1. Filter line layer with expression of unsorted list (probably use layer.setSubsetString() method)
  2. Get destination feature point xy value (use feature.geometry().centroid().asPoint() mehtod)
  3. Use the spatial index nearestNeighbor() method to return a list of closest feature ids, see the answer in this q/a below.
  4. Get length of unsorted list (from line layer) in second parameter of nearestNeighbor() method

Finding nearest line to point in QGIS?

This should provide you a list of order of nearest features (you may reverse the list order get from farthest to nearest from A->B)).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy