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())