SHARE
TWEET

Points-to-lines-script_QGIS3

a guest Jul 15th, 2019 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from qgis.PyQt.QtCore import QVariant
  2.  
  3. # variables
  4. layer_name = "My_layer_name"
  5. line_field_name = "Line"
  6. m_threshold = 0.5
  7. new_name = "new_lines"
  8. order_variable="Fiducial"
  9.  
  10. # find point vector layer
  11. vl = QgsProject.instance().mapLayersByName(layer_name)[0]
  12.  
  13. # create a new line layer
  14. crs = vl.crs().authid()
  15. vline = QgsVectorLayer("multilinestring?crs=" + crs, new_name , "memory")
  16. pr = vline.dataProvider()
  17. pr.addAttributes([QgsField(line_field_name, QVariant.String)])
  18. vline.updateFields()
  19.  
  20. new_geometry = QgsGeometry()
  21.  
  22. idx = vl.fields().indexOf(line_field_name)
  23. line_values = vl.uniqueValues(idx)
  24.  
  25. for line in line_values:
  26.     # init for
  27.     expr = QgsExpression('"' + line_field_name + '"= \'' + line + '\'')
  28.     request = QgsFeatureRequest(expr)
  29.     request.addOrderBy(order_variable)
  30.     wkt = "MultiLineString (("
  31.     previous_linename = None
  32.     previous_geometry = None
  33.  
  34.     for feat in vl.getFeatures(request):
  35.  
  36.         if previous_linename is not None:
  37.             segment = feat.geometry().shortestLine(previous_geometry)
  38.  
  39.             if segment.length() > m_threshold:
  40.                 # delete last comma and begin next part
  41.                 wkt = wkt[:-1] + "),("
  42.  
  43.             pt = feat.geometry().asPoint()
  44.             wkt += str(pt.x()) + " " + str(pt.y()) + ","
  45.  
  46.         previous_linename = line
  47.         previous_geometry = feat.geometry()
  48.         pt = feat.geometry().asPoint()
  49.         wkt += str(pt.x()) + " " + str(pt.y()) + ","
  50.        
  51.  
  52.     # delete last comma and close wkt
  53.     wkt = wkt[:-1] + "))"
  54.     new_feat = QgsFeature()
  55.     new_feat.setGeometry(QgsGeometry.fromWkt(wkt))
  56.     new_feat.setAttributes([previous_linename])
  57.     pr.addFeature(new_feat)
  58.  
  59. # update extent for the new line layer
  60. vline.updateExtents()
  61. # load new line layer to canvas
  62. QgsProject.instance().addMapLayer(vline)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top