Thursday, 13 September 2018

pyqgis - Finding nearest line to point in QGIS?



Given a point and few lines, how should I go about finding the nearest line to the point?


enter image description here



I am aware of Finding nearest line to point using ArcGIS Desktop (ArcObjects/ArcPy)?, but that is in ArcGIS and uses its functions.




The "duplicate" question doesn't answer this question properly, it's just a pointer to MMQGIS.



Answer



You can use QgsSpatialIndex class for finding nearest objects. First you will need to create a new object of this class. Then add the required features to the index. Then you should be able to use QgsSpatialIndex.nearestNeighbor (QgsPoint point, int neighbors) moethod to retrieve the nearest ones.


Here is sample that I managed in python console.


lineLayer = iface.activeLayer()
provider = lineLayer.dataProvider()

spIndex = QgsSpatialIndex() #create spatial index object


feat = QgsFeature()
fit = provider.getFeatures() #gets all features in layer

# insert features to index
while fit.nextFeature(feat):
spIndex.insertFeature(feat)

pt = QgsPoint(-0.00062201,0.00001746)


# QgsSpatialIndex.nearestNeighbor (QgsPoint point, int neighbors)
nearestIds = spIndex.nearestNeighbor(pt,1) # we need only one neighbour
print nearestIds

Edit:


To get the actual QgsFeature object from the python list, you can do this,


featureId = nearestIds[0]
fit2 = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId))
ftr = QgsFeature()
fit2.nextFeature(ftr)

# ftr now contains the QgsFeature object for the id

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...