I'm working on this script in PyQGIS to take points from a layer called LEK_ALL and snap them to the closest feature of a line layer called LEID_filtered which fulfills a certain request.
In order to do so, I created the function
snapPointToLine. This is the full code:
from qgis.PyQt.QtGui import * from qgis.PyQt.QtWidgets import * from qgis.PyQt.QtCore import * from qgis.core import * import os def snapPointToLine(feature, lineLayer, request, AttrID): ''' QgsFeature (point), QgsLayer (lines), QgsFeatureRequest, list -> QgsFeature Takes the feature feature and snaps it to the colest point of the feature in layer lineLayer that fullfills request. Returns the new feature with the same attributes as the old ones, plus the attributes of the snapped-to feature with indices in AttrID. ''' pt = feature.geometry().asPoint() lineIter = lineLayer.getFeatures(request) #iterator of the features in lineLayer fulfilling the request spIndex = QgsSpatialIndex(lineIter) #create spatial index from selected feature nearestIds = spIndex.nearestNeighbor(pt,1) #list of 1 closest neighbour featureId = nearestIds #item 0 (and only) of the list is the id nearestIterator = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId)) #generate iterator containing only the closest feature nearFeature = QgsFeature() #generate an empty feature nearestIterator.nextFeature(nearFeature) #copy information from nearestIterator to nearFeature closeSegResult = nearFeature.geometry().closestSegmentWithContext(pt) #results in a description of the closest segment between the nearFeature and point closePoint = closeSegResult #closest point on geometry to LEK #generate feature in new location newFeature = QgsFeature() newFeature.setGeometry(QgsGeometry.fromPoint(QgsPoint(closePoint,closePoint))) newFeature.setAttributes(feature.attributes() + [nearFeature.attributes()[i] for i in AttrID]) return newFeature registry = QgsMapLayerRegistry.instance() LEK = registry.mapLayersByName('LEK_ALL') LEID = registry.mapLayersByName('LEID_filtered') LEKIter = LEK.getFeatures() Date_id = LEK.fieldNameIndex('Date') #gets id of field "Date" LEID_id = LEID.fieldNameIndex('AssetNum') #gets id for field "AssetNum" newFeat_list =  #generate new empt list to save the new features for feature in LEKIter: LEKDate = feature.attributes()[Date_id] #get failure date y,m,d = LEKDate.year(),LEKDate.month(),LEKDate.day() #split it into components request_str = u'"InstYear" <= to_date(\'%d-%02d-%02d\') AND "RemDate*" >= to_date(\'%d-%02d-%02d\')' % (y,m,d,y,m,d) #generate query pt.1 request = QgsFeatureRequest().setFilterExpression(request_str) #generate query pt.2 newFeature = snapPointToLine(feature, LEID, request, [LEID_id]) newFeat_list.append(newFeature)
When I run it I get the following error:
NameError: global name 'QgsSpatialIndex' is not defined
Associated to the line
spIndex = QgsSpatialIndex(lineIter) #create spatial index from selected feature