I'm using QGIS 3.4 on Windows 10 and scripting in pyqgis. I have a layer representing building centroids that is in a projected CRS. I want to find the azimuth between each building and its nearest neighbour in the same layer, so the input and target points being in the correct order is important. However, when I run the following script the closest pairs are output each time with the points in the same order rather than reversed. This renders the output useless. I have tried changing the parameters for MATRIX_TYPE but have kept the other parameters as shown. The data is a vector point layer in projected format.
import os
import ogr
from qgis.core import (
QgsVectorLayer,
QgsProject,
QgsProperty
)
import processing
QgsProject.instance().removeAllMapLayers() # remove all of the layers from the active map
Building_centroids = QgsVectorLayer('C:/Users/ADMIN/Desktop/Mod04AssessedEx/data/bldg_centroids.shp', "Building_centroids", "ogr") # create vector layer, ogr (or something else) needed
if not Building_centroids.isValid():
print("Layer failed to load!")
QgsProject.instance().addMapLayer(Building_centroids) # add layer to map
distance_matrix = processing.run("qgis:distancematrix",
{
'INPUT': Building_centroids,
'INPUT_FIELD': 'OBJECTID',
'TARGET': Building_centroids,
'TARGET_FIELD': 'OBJECTID',
'MATRIX_TYPE': 0,
'NEAREST_POINTS': 1,
'OUTPUT': 'memory:'
}
)['OUTPUT']
QgsProject.instance().addMapLayer(distance_matrix) # adds the results as a temporary layer to the active map
# this calculates the azimuth between each structure and its nearest neighbour
for structure in distance_matrix.getFeatures():
structure_geometry = structure.geometry()
print (structure_geometry)
structure_geometry = structure.geometry().asMultiPoint()# this line unpacks the multipoint geometry into an iterable or indexable list
print(structure_geometry[0])
print(structure_geometry[1])
azimuth_2_neighbour = structure_geometry[0].azimuth(structure_geometry[1]) # is this working?? no buildings are due west of their nearest neighbour, or is that coincidence
print(azimuth_2_neighbour)