0

I have a track (Line) and I want to know wich countrys/cities (Polygon) intersect this track.

I try in two ways:

a) With PyQgis - I use QgsSpatialIndex().intersects(track.geometry().boundingBox())

            for track in layer_track.getFeatures():
                 # Find Features
                 index = QgsSpatialIndex()
                 index = QgsSpatialIndex(layer_to_intersect.getFeatures())
                 find_result = index.intersects(track.geometry().boundingBox())

b) With Qgis console - Join Atributtes by Location

And the results was in both cases are:

Results

As you can see in the image there are polygons that are not intersected by the line and appear in the search results.

The correct result should be as in the following image:

Correct Result

I understand what happens, and that is that to do the search, the line becomes a rectangle, and the result of the operation shows the polygons that intersect this rectangle.

And this is not the result of what I am looking for.

I am thinking of converting the line to points and seeing what points intersect with the polygons and thus have a satisfactory result.

When I work with Arcgis I use Spatial_Join to do this, and the results was satisfactory.

Any idea to help me?

0

1 Answer 1

0

Case a)

You make an intersect between the bounding box from your track so it will return all polygons that intersect your line bounding box. So, that's why you get "wrong" results. Using index is a good way to reduce the number of results but then you need for each feature id from find_result to filter your polygon features with exact geometry using something like below

final_result = [feature for feature in layer_to_intersect.getFeatures(find_result) if track.geometry().intersects(feature.geometry())]

PS: I didn't invent the reason: in https://www.qgis.org/api/classQgsSpatialIndex.html#a58c6e5ac1ef78551ecf0757d835da0ee they tell you the following

The intersection test is performed based on the feature bounding boxes only, so for non-point geometry features it is necessary to manually test the returned features for exact geometry intersection when required.

Case b)

You don't use the right algorithm. "Join attributes by location" set in the resulting polygons the attributes from your track but does not filter them (they are all returned) You should better use "Extract by location". It works (tested with QGIS 3.12)

1
  • Works perfect!!! Thank you so much.@ThomasG77
    – RBenet
    Commented May 16, 2020 at 7:20

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.