Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

This question already has an answer here:

My question is that 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 How to I find the nearest line to a point?, but that isin ArcGIS and uses it's functions.

Thanks

Edit: the "duplicate" question doesn't answer this question properly, it's just a pointer to mmgis.

share|improve this question

marked as duplicate by Devdatta Tengshe, whuber Apr 26 '13 at 13:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
After you've found the nearest line, what do you want to do with it? –  R.K. Apr 26 '13 at 2:03
    
@R.K. Then I want to find the perpendicular distance from the point to that line –  PeterBorook Apr 26 '13 at 2:21
2  
There has been some solution in QGIS mailing list a few years ago:lists.osgeo.org/pipermail/qgis-user/2010-May/008745.html. Carson provide "meta-python-code": –  posiki Apr 26 '13 at 5:21
add comment

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer
    
Thanks for introducing me to QgsSpatialIndex! it all looks wonderful; just let me ask a further question: How can I get the actual feature in "lineLayer" from this "nearestIds"?( i.e. get featureid from indexid?) –  PeterBorook Apr 26 '13 at 6:50
    
@PeterBorook - i updated the answer..the code is based on version 1.9. If you need to get it working for older version, please refer qgis.org/pyqgis-cookbook –  vinayan Apr 26 '13 at 7:19
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.