TransWikia.com

Saving attributes information (features) in QGIS layer

Geographic Information Systems Asked on November 1, 2021

I have a road network (lines) and points (Address). I am using PyQGIS to join points to the nearest lines using the closestSegmentWithContext functionin QGIS. However, the attribute table of generated layer (myLayer) is empty as shown here. Is there a way to save all features(fields) of joining points like unique IDs, lengths of joining points, etc in the attribute table of vector layer?

I searched about FileWriter in QGIS, but it didn’t solve my purpose, or I might not apply correctly.
The PyQGIS code for joining line segements to nearest points is given below and shape files are available here:

roadlyr = QgsProject.instance().mapLayersByName('TR_ROAD')[0]
addrlyr = QgsProject.instance().mapLayersByName('ADDRESS')[0]

#List all features
adresses = [f for f in addrlyr.getFeatures()]
roads = [f for f in roadlyr.getFeatures()] 

#Create vector layer
vl = QgsVectorLayer("LineString?crs={}&index=yes".format(roadlyr.crs().authid()), "myLayer", "memory")
provider = vl.dataProvider()

for adress in adresses:
    a = min([road.geometry().closestSegmentWithContext(adress.geometry().asPoint()) for road in roads], key=lambda x: x[0]) #For each road find closest address
    gLine = QgsGeometry.fromPolyline([QgsPoint(adress.geometry().asPoint()), QgsPoint(a[1])])
    f = QgsFeature()
    f.setGeometry(gLine)
    provider.addFeature(f)

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP