[GIS] NNJoin, MMQGIS and Nearest Neighbor QGIS failed to measure shortest distance

distanceqgis

I have two layers, one point and one line. I need the distance to the closest line from the point layer. Not NNJoin, MMQGIS nor the distance hub in QGIS provided accurate measures. Any ideas?

Best Answer

If you have to measure the distances once again, the following Python code may save you some time.

Have your points and lines loaded as map layers. Change the names 'point' and 'line' in line 4 and 5 resp. to the names of your layers. Copy the code into the Python console.

The function iterates over all points and finds the closest segment of all lines, and writes the closest position along the segment to a list. Then takes the position with the minimum distance to a points and builds a connecting line. The length of the line goes to the field distance.

d_lyr = QgsVectorLayer('LineString?field=distance:float', 'dist', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(d_lyr)

p_lyr = QgsMapLayerRegistry.instance().mapLayersByName('point')[0]
l_lyr = QgsMapLayerRegistry.instance().mapLayersByName('line')[0]
d_lyr = QgsMapLayerRegistry.instance().mapLayersByName('dist')[0]
prov = d_lyr.dataProvider()
feats = []      
for p in p_lyr.getFeatures():
    minDistPoint = min([l.geometry().closestSegmentWithContext(QgsPoint(p.geometry().asPoint())) for l in l_lyr.getFeatures()])[1]
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromPolyline([QgsPoint(p.geometry().asPoint()), QgsPoint(minDistPoint[0], minDistPoint[1])]))
    feat.setAttributes([feat.geometry().length()])
    feats.append(feat)

prov.addFeatures(feats)
d_lyr.updateExtents()
d_lyr.triggerRepaint()

To test the code initiate 2 memory layers, a point layer named 'point' and a line layer named 'line', digitize some features, and run the code.

An example:

enter image description here