[GIS] Calculate azimuth of vector for QGIS 2.0 Python plugin

pyqgispythonqgis

I calculate the azimuth of a vector and update a field in my QGIS 2.0 Python 2.7 plugin. This works currently, but it takes much longer than i'd like to. I believe it is because i'm querying the data source on every call. Any suggestions on updating the fields all in one go as was suggested in another one of my questions? I'm having issues trying to adapt the suggestion for this particular evaluate function.

    self.rotateLayer.startEditing()
    bear_idx = self.rotateLayer.fieldNameIndex('angleRot')
    bearCalc = QgsExpression('(atan((xat(-1)-xat(0))/(yat(-1)-yat(0)))) * 180/3.14159 + (180 *(((yat(-1)-yat(0)) < 0) + (((xat(-1)-xat(0)) < 0 AND (yat(-1) - yat(0)) >0)*2)))')
    bearCalc.prepare(self.rotateLayer.pendingFields())
    for fields in self.rotateLayer.getFeatures():
        fields[bear_idx] = bearCalc.evaluate(fields)
        self.rotateLayer.updateFeature(fields)
    self.rotateLayer.commitChanges()

Best Answer

I don't know what you are trying to do. In PyQGIS, the azimuth of a vector is given by

line_start_point.azimuth(line_end_point)

Look at How to add Direction and Distance to attribute table?, How do I find vector line bearing in QGIS or GRASS? or Create Intersecting lines and remove dangles

Related Question