3

I did assume that the answer was yes, but I have developed some doubts about that because I observe something which seems to contradict:

I have a netlayer containing road segments (LineStrings) with a corresponding spatial index netindex. Now I wish to find the closest segment to a given QgsPoint pt.

I use the netindex.nearestNeighbor(pt,n) to obtain the corresponding featureIds:

req = QgsFeatureRequest(); 
req.setFilterFids(netindex.nearestNeighbor(pt,n))
fs = [f for f in netlayer.getFeatures(req)]
closestEdgeGeoms = [f.geometry() for f in fs]
ptGeom = QgsGeometry.fromPoint(pt)
dists = [g.distance(ptGeom) for g in closestEdgeGeoms]

Now let's have a look what the dists are for increasing n:

n=1 # -> dists=[132.57922743885197]
n=2 # -> dists=[44.65094179417814, 132.57922743885197], ups!?
n=3 # -> dists=[232.91196346783073, 44.65094179417814, 132.57922743885197]
n=4 # -> dists=[186.9821211234746, 232.91196346783073, 44.65094179417814, 132.57922743885197], again found sth closer...
...

That's it. Does someone have an idea how large n should be to guarantee to catch the closest geometry? Or is this a bug?


Edit: As Steven pointed out this question is related. My question is actually answered by Håvard Tveite's answer.

Leolo
  • 193
  • 5
  • Which is the problem with this code? It seems that, for n increasing, the new item in the dists list is larger than the previous ones... Or, probably, I don't understand what are you asking. – mgri Mar 29 '17 at 12:58
  • No. The new items appear on the left of the list (mysteriously...). So actually, the segment at 44m. distance is found after the one at 132m. distance. – Leolo Mar 29 '17 at 18:50
  • 2
    i think this question might be related, assuming you're only asking for n=1 and sometimes getting more edges – Steven Kay Mar 29 '17 at 21:18
  • Thanks for pointing me there! See edit. I have not enough reputation to comment Havard's answer so he notices that he answered the question... :( – Leolo Mar 30 '17 at 06:50
  • @Leolo Sorry, I didn't notice it and you are right. However, I think that the link provided by @ StevenKay should answer to your issue. – mgri Mar 30 '17 at 07:03

0 Answers0