PYTHON 10
QGIS - Script - Connect All Points By Lines By mike on 30th November 2021 01:02:01 AM
  1. """
  2. Source : https://gis.stackexchange.com/questions/366235/creating-all-possible-line-segments-between-all-points-using-qgis
  3. Create new script in the Scripts menu at the top of the Processing Toolbox to open the Processing Script Editor where you can write your code.
  4.  
  5. You can use the same layer as source and target or use two different layers. A unique attribute is required to run it.
  6. The script returns lines connecting all points including the unique attributes of both layers, or the unique attribute of the only layer. Also the line length is added as attribute.
  7. The advantage of this method is, that it can easily be used within graphical modeler.
  8. """
  9. from PyQt5.QtCore import QCoreApplication, QVariant
  10. from qgis.core import (QgsField, QgsFeature, QgsProcessing, QgsExpression, QgsGeometry, QgsPoint, QgsFields, QgsWkbTypes,
  11.                        QgsFeatureSink, QgsFeatureRequest, QgsProcessingAlgorithm,
  12.                        QgsProcessingParameterFeatureSink, QgsProcessingParameterField, QgsProcessingParameterFeatureSource, QgsProcessingParameterEnum)
  13.  
  14. class ConnectAllPointsByLines(QgsProcessingAlgorithm):
  15.     POSSIBILITY_LYR = 'POSSIBILITY_LYR'
  16.     POSSIBILITY_IDFIELD = 'POSSIBILITY_IDFIELD'
  17.     STOP_LYR = 'STOP_LYR'
  18.     STOP_IDFIELD = 'STOP_IDFIELD'
  19.     OUTPUT = 'OUTPUT'
  20.  
  21.     def initAlgorithm(self, config=None):
  22.        
  23.         self.addParameter(
  24.             QgsProcessingParameterFeatureSource(
  25.                 self.STOP_LYR, self.tr('Source Points'), [QgsProcessing.TypeVectorPoint]))
  26.         self.addParameter(
  27.             QgsProcessingParameterField(
  28.                 self.STOP_IDFIELD, self.tr('Unique ID Field of Source Layer (Any Datatype)'),'ANY','STOP_LYR'))        
  29.         self.addParameter(
  30.             QgsProcessingParameterFeatureSource(
  31.                 self.POSSIBILITY_LYR, self.tr('Target Points'), [QgsProcessing.TypeVectorPoint]))
  32.         self.addParameter(
  33.             QgsProcessingParameterField(
  34.                 self.POSSIBILITY_IDFIELD, self.tr('Unique Target ID Field (Any Datatype, should have a different name than Source ID field)'),'ANY','POSSIBILITY_LYR'))
  35.         self.addParameter(
  36.             QgsProcessingParameterFeatureSink(
  37.                 self.OUTPUT, self.tr('Line Connections'), QgsProcessing.TypeVectorLine))
  38.  
  39.     def processAlgorithm(self, parameters, context, feedback):
  40.         # Get Parameters
  41.         possibility_layer = self.parameterAsSource(parameters, self.POSSIBILITY_LYR, context)
  42.         possibility_idfield = self.parameterAsFields(parameters, self.POSSIBILITY_IDFIELD, context)
  43.         stop_layer = self.parameterAsSource(parameters, self.STOP_LYR, context)
  44.         stop_idfield = self.parameterAsFields(parameters, self.STOP_IDFIELD, context)
  45.  
  46.         fields = QgsFields()
  47.         fields.append(QgsField(stop_idfield[0]))        
  48.         fields.append(QgsField(possibility_idfield[0]))
  49.         fields.append(QgsField("line_length", QVariant.Double, len=20, prec=5))
  50.  
  51.         (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
  52.                                                fields, QgsWkbTypes.LineString,
  53.                                                possibility_layer.sourceCrs())
  54.  
  55.         # iterate over stop features
  56.         for stop_feat in stop_layer.getFeatures():
  57.             point1 = QgsPoint(stop_feat.geometry().asPoint())
  58.             for source_feat in possibility_layer.getFeatures():
  59.                 point2 = QgsPoint(source_feat.geometry().asPoint())
  60.                 new_feat = QgsFeature(fields)
  61.                 new_feat.setGeometry(QgsGeometry.fromPolyline([point1, point2]))
  62.                 new_feat[stop_idfield[0]] = stop_feat[stop_idfield[0]]                
  63.                 new_feat[possibility_idfield[0]] = source_feat[possibility_idfield[0]]
  64.                 new_feat["line_length"] = new_feat.geometry().length()                
  65.                 sink.addFeature(new_feat, QgsFeatureSink.FastInsert)
  66.            
  67.         return {self.OUTPUT: dest_id}
  68.  
  69.  
  70.     def tr(self, string):
  71.         return QCoreApplication.translate('Processing', string)
  72.  
  73.     def createInstance(self):
  74.         return ConnectAllPointsByLines()
  75.  
  76.     def name(self):
  77.         return 'ConnectAllPointsByLines'
  78.  
  79.     def displayName(self):
  80.         return self.tr('Connect All Points By Lines')
  81.  
  82.     def group(self):
  83.         return self.tr('From Michael van Wijk')
  84.  
  85.     def groupId(self):
  86.         return 'from_mvw'
  87.  
  88.     def shortHelpString(self):
  89.         return self.tr('This Algorithm connects all points of the Source layer with all points of the Target layer with lines and adds the lines length')

Hasta la pasta! is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.