I saw Finding the nearest line to a point in QGIS?
I wanted to create a program to get the line closest to the selected point.
Here is the code.
dPos = mouseEvent.pos()
qpoint = self.get_canvas_point(dPos)
layer = self.iface.activeLayer()
features = layer.getFeatures()
SpInd = QgsSpatialIndex(features)
nearestSpIndids = SpInd.nearestNeighbor(qpoint,2)
for nearestid in nearestSpIndids:
gettingfeatures = layer.getFeatures(QgsFeatureRequest(nearestid))
for feat in gettingfeatures:
#feature_check
prop1 = feat['PEN_Color']
prop2 = feat['ID']
root = QTreeWidgetItem()
root.setText(0,str(prop1) +':' + str(prop2))
self.dlg.treeWidget.addTopLevelItem(root)
However, even if I select any places, "Specific" lines will be selected.
For example : Regardless of where on the map you choose, you can only get information on the red line.
Is there anything strange about code?
