[GIS] Why does QgsSpatialIndex.nearestNeighbor(point, 1) sometimes return 2 lines

nearest neighborpyqgispythonqgis

I'm trying to get the closest line to a point using PyQGIS in a plugin. The active code file is this: http://pastebin.com/TDzmsKVM

When I request the closest line (only 1)

nearestIds = self.spIndex.nearestNeighbor(self.feat2.geometry().centroid().asPoint(),1)

I sometimes get a list with two lines and the first one is not the closest but as far as I can see the second one is. Why is this?

Does QgsSpatialIndex use only boundingboxes for lines?
How do I get the real closest line always, not only most of the time?

Best Answer

The nearest points can return more then one according to the underlying code. RTree.cc (a underlaying file)

539  // report all nearest neighbors with equal greatest distances.
540  // (neighbors can be more than k, if many happen to have the same greatest distance).

The greatest distance I guess should be the smallest. But other then that it sounds like a truncation in the tree precision.

Related Question