34 lines
1.4 KiB
Python
34 lines
1.4 KiB
Python
|
from qgis.core import (QgsFeature, QgsField, QgsVectorLayer, QgsProject, QgsSpatialIndex)
|
||
|
|
||
|
print("Associating home points to drop points...")
|
||
|
|
||
|
# Load the NODES and HOME_POINT layers
|
||
|
nodes_layer = QgsProject.instance().mapLayersByName('NODES')[0]
|
||
|
home_points_layer = QgsProject.instance().mapLayersByName('HOME_POINTS')[0]
|
||
|
|
||
|
# Prepare the drop_point_id field for the HOME_POINT layer
|
||
|
home_points_layer.startEditing()
|
||
|
home_points_prov = home_points_layer.dataProvider()
|
||
|
home_points_prov.addAttributes([QgsField("drop_point_id", QVariant.Int)])
|
||
|
home_points_layer.updateFields()
|
||
|
|
||
|
# Build a spatial index for the NODES layer
|
||
|
index = QgsSpatialIndex()
|
||
|
node_features = {f.id(): f for f in nodes_layer.getFeatures()}
|
||
|
index.addFeatures(node_features.values())
|
||
|
|
||
|
# Find the nearest node for each home point and update the drop_point_id attribute
|
||
|
for hp in home_points_layer.getFeatures():
|
||
|
nearest_nodes = index.nearestNeighbor(hp.geometry().asPoint(), 1)
|
||
|
if nearest_nodes:
|
||
|
nearest_node_id = nearest_nodes[0]
|
||
|
nearest_node = node_features[nearest_node_id]
|
||
|
node_id = nearest_node["id"]
|
||
|
home_points_layer.changeAttributeValue(hp.id(),
|
||
|
home_points_layer.fields().indexOf("drop_point_id"),
|
||
|
node_id)
|
||
|
|
||
|
# Stop editing the HOME_POINT layer and save changes
|
||
|
home_points_layer.commitChanges()
|
||
|
|
||
|
print("Done.")
|