Finding which side of closest polyline point lies on in QGIS?
Not a single query but the following code can be executed in the Python Console. The code essentially does the following:
- Iterates each line feature and calculates the distance from this to a selected point feature;
- Stores these in a dictionary;
- A proximity is used to limit iterating through each line feature (i.e. a value of 100 means only lines within 100m of the point will be included);
- Sorts the dictionary and selects the line feature with the minimum distance from the point;
- Gets the coordinates of the start and end vertices;
- Determines if the point lies on the left- or right-hand side of the line (assuming the line is a single straight line).
pointLayer = QgsProject.instance().mapLayersByName('point')[0]
lineLayer = QgsProject.instance().mapLayersByName('line')[0]
# Set proximity limit
proximity = 1
distance_dict = {}
for point in pointLayer.selectedFeatures():
start_point = point.geometry().asPoint().x()
end_point = point.geometry().asPoint().y()
for line in lineLayer.getFeatures():
distance = point.geometry().distance(line.geometry())
if distance < proximity:
distance_dict[line.id()] = distance
closestFeature = sorted(distance_dict.keys(), key=(lambda key: distance_dict[key]))
lineLayer.selectByIds([closestFeature[0]])
for line in lineLayer.selectedFeatures():
start_geom = line.geometry().asPolyline()[0]
end_geom = line.geometry().asPolyline()[1]
d = ((start_point - start_geom.x()) * (end_geom.y() - start_geom.y())) - (((end_point - start_geom.y()) * (end_geom.x() - start_geom.x())))
if d < 0:
print('Left')
elif d > 0:
print('Right')
else:
print('On line')
Example of selected points (highlighted in yellow):
Right of line -
Left of line -