1

I have road network (lines) and points (Address) . With the help of closestSegmentWithContext function, I join points to nearest lines in QGIS. Is there a way to to generate a unique ID at every joining point as the joining points are drawn manually in below image.

What I have researched so far:

  • Found a possible solution here, but it didnt worked for joining points.
  • I come accross a useful plugin "AUTOFIELD" in anwer here, but this plugin is no more avaible in QGIS 3.XX

enter image description here

The 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 empty 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)

QgsProject.instance().addMapLayer(vl)
2
  • 2
    Use the Default value functionality that comes with QGIS 3 (that's why AutoFields was never migrated to QGIS 3): user-images.githubusercontent.com/652785/… As expression, you can use something like uuid(). Make sure Apply default value on update is not checked, so that the uuid() is generated only when the feature is created. Jul 21, 2020 at 2:45
  • @GermánCarrillo.Thank you for great suggestion. I able to generate UUID. The other difficulty is when i use closestSegmentWithContext function in above code in question to join the points to nearest lines, the attribute table (myLayer) is empty as shown ibb.co/cDCjdhC . Is there a way to save all features of joining points like unique IDs, lengths of joining points etc in the attributr table. I am trying to generate UUID of every joing point inside attribute table.
    – Case Msee
    Jul 21, 2020 at 3:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.