# Draw Bridges at intersections with correct angle with PyQGIS?

I have a road layer and a river layer. I want to draw bridges at the intersections with correct orientation of the bridge (parallel to the road).

I have found out that you can use the "Vector->Analysis Tools->Line Intersections" to identify the intersections. But how do I identify the angle of the road layer at this exact point and automatically roate it acordingly?

I have found this rotate point along line layer, they suggested to use the following code:

from math import atan2

# get layers
bridges = QgsMapLayerRegistry.instance().mapLayersByName('bridges')[0]
trails = QgsMapLayerRegistry.instance().mapLayersByName('trails')[0]

# get fieldindex
fni = bridges.fieldNameIndex('angle')

# initializations
tolerance = 0.01  # search tolerance
bridges.startEditing()

# loop over all bridges
for bridge in bridges.getFeatures():
x = bridge.geometry().asPoint().x()
y = bridge.geometry().asPoint().y()

# get the rectangular search area
searchRect = QgsRectangle(x - tolerance, y - tolerance,  x + tolerance, y + tolerance)

# find trails
for trail in trails.getFeatures(QgsFeatureRequest().setFilterRect(searchRect)):
# get the nearest vertex on trail and the one before and after
pnt, v, b, a, d = trail.geometry().closestVertex(bridge.geometry().asPoint())
p1 = trail.geometry().vertexAt(v)
# when vertex before exists look back, otherwise look forward
if v>-1 and b>-1:
p2 = trail.geometry().vertexAt(b)
elif v>-1 and a>-1:
p2 = trail.geometry().vertexAt(a)

# calculate azimuth
angle = atan2(p2.x() - p1.x(), p2.y() - p1.y()) / 0.017453
bridge[fni] = angle
bridges.updateFeature(bridge)

# save changes and stop editing
bridges.commitChanges()

I followed the steps however I get an error for line 15 like so

File "<input>", line 15
bridges.commitChanges()
^
SyntaxError: invalid syntax

Line 15 is:

pnt, v, b, a, d = trail.geometry().closestVertex(bridge.geometry().asPoint())
• Yes, except that i replace bridges and trails with the name of the two layers representing those two. I created the angle attribute as a decimal number with the length of 9 and precicion of 3 in the trails shapefile. I use QGIS 2.14.11 – Lukas Sep 8 '17 at 11:36
• I know. It works for me now, I needed to import it into the editor and execute it from there, somehow importing it directly into the execution console produced a lot of errors. Thank you for encouraging me to try it once more – Lukas Sep 8 '17 at 11:48
• Ok, introduce code snippets in the console is a little be tricky yes... Glad you find the solution. Could you post it as an answer? Then we can delete all these unnecessarys comments and the question won't remains unanswered. Thk's – YoLecomte Sep 8 '17 at 11:55