In this recipe, we will use the QGIS network analysis library from Python console to match points to the nearest line. This is the simplest form of what is also known as map matching.
The following script will match three points, QgsPoint(3.63715,3.60401), QgsPoint(3.86250,1.58906), and QgsPoint(0.42913,2.26512), to the network:
network_analysis_match_points.py script:import processing
from processing.tools.vector import VectorWriter
from PyQt4.QtCore import *
from qgis.core import *
from qgis.networkanalysis import *
layer = processing.getObject('network_pgr')
director = QgsLineVectorLayerDirector(layer,-1,'','','',3)
director.addProperter(QgsDistanceArcProperter())
builder = QgsGraphBuilder(layer.crs())
additional_points = [QgsPoint(3.63715,3.60401),QgsPoint(3.86250,1.58906),QgsPoint(0.42913,2.26512)]
tied_points = director.makeGraph(builder,additional_points)
result = 'C:\\temp\\matched_pts.shp'
writer = VectorWriter(result,None,[],1,layer.crs())
fet = QgsFeature()
for pt in tied_points:
fet.setGeometry(QgsGeometry.fromPoint(pt))
writer.addFeature(fet)
del writer
processing.load(result)This script uses the QGIS network analysis library's ability to match points to lines using the makeGraph() function. The resulting tied_points list contains the coordinates of the points on the network that are closest to the input points.
The 1 option on line 15 specifies that the output layer is of type point.
The for loop finally goes through all points in the tied_points list and creates point features, which are then added to the result writer.