I am currently writing an Python script within QGIS to connect points of two specific point layers:
For each point in point-layer1, the python script loops over all points of point-layer2 and compares the attribute
"direction" (of point-layer1) with the attribute
"location" (of point-layer2). If they are equal, a new line should be created and stored into the output line-layer (together with the
"lineID" (a line counter) and the direction name + location name).
Here is my Python Script:
# name : ConnectPointsByValue_script # date : 27.12.2017 # description: connects points from evis with points of location_coordinates # if the attributes "direction" and "location" are equal from PyQt4.QtCore import QVariant from qgis.core import * from PyQt4.QtCore import * #***********Constants # LINEID = 'lineID' POINTID1 = 'pointID_Location' POINTID2 = 'pointID_Direction' # #*********** # input parameters ##Counters=vector ##Locations=vector inputLayerCounters = processing.getObject(Counters) inputLayerLocations = processing.getObject(Locations) crs = inputLayerCounters.crs().toWkt() # Create the output layer outLayer = QgsVectorLayer('Linestring?crs='+ crs, 'connector_lines2' , 'memory') outdp = outLayer.dataProvider() #get the field index outLineID = outdp.fieldNameIndex(LINEID) outID1 = outdp.fieldNameIndex(POINTID1) outID2 = outdp.fieldNameIndex(POINTID2) lineIDcnt = 0 # loop through points of iCounters and connect each point with the matching location point for feat1 in inputLayerCounters.getFeatures(): geom1 = feat1.geometry() #loop all points from iLocations for feat2 in inputLayerLocations.getFeatures(): geom2 = feat2.geometry() # get the feature's attributes attrs1 = feat1.attributes() idx1 = inputLayerCounters.fieldNameIndex('direction') attrs2 = feat2.attributes() idx2 = inputLayerLocations.fieldNameIndex('location') #check if attributes are equal if feat1.attributes()[idx1] == feat2.attributes()[idx2]: lineIDcnt += 1 #if true: create line and add to output line layer connector = QgsFeature(outLayer.pendingFields()) connector.setGeometry(QgsGeometry.fromPolyline([geom1.asPoint(), geom2.asPoint()])) #record the IDs res = connector.setAttribute(outLineID, lineIDcnt) res = connector.setAttribute(outID1, feat1.attributes()[idx1]) res = connector.setAttribute(outID2, feat2.attributes()[idx2]) #add the feature to the layer res = outdp.addFeatures([connector]) # Add the layer to the Layers panel QgsMapLayerRegistry.instance().addMapLayer(outLayer) print "Done .. "
If I execute this script, I get an error which says:
attribute index -1 out of bounds [0;0]
I think I am doing something wrong with indexing the attributes of my points. Any suggestions on how to solve this?