I am trying to update a field in a (Road centerline) table based on a value from another table when it is within a Polygon (Locality boundaries).
Based on posts like QGIS layer.geometry.intersection() not finding intersections between layers I have the following code. Both datasets are in EPSG:28355. It never prints ntext=b['Locality_N'] - so obviously something is wrong with the if within statement.
import re
def Update_Field(fieldName, ntext): # Function to simplify updating fields
print (ntext)
fieldIndex = layer.fields().indexFromName(fieldName)
dpr.changeAttributeValues({f.id(): {fieldIndex: ntext}})
layer.commitChanges()
RoadType_dict = {'Rd':'Road', 'Avenue': 'Ave'}
layer = iface.activeLayer()
selection = layer.getFeatures() #all features
#selection = layer.selectedFeatures() #only selected features
#Locality Data
Locality_layer=QgsVectorLayer(r'Z:\My Drive\Mangoesmapping\Spatial Projects\Gen_Library\DSC\vector\DSC_Localities_areas.shp', "Locality", "ogr")
dpr = layer.dataProvider()
for f in selection:
print (f.id())
text=f['RoadMntnc']
print (text)
stext=re.split('_+', text)
##Update Road Type
# ntext=RoadType_dict.get(stext[-1:][0])
# fieldName='Type'
# Update_Field(fieldName,ntext)
##Update LocalityName
for b in Locality_layer.getFeatures():
if f.geometry().within(b.geometry()):
print (b.geometry())
ntext=b['Locality_N']
fieldName="Locality"
Update_Field(fieldName,ntext)
layer.commitChanges()
layer.updateFields()
I have commented out the code that works but is not required for these tests.
--- Based on another answer I also tried
e = QgsExpression( "geomwithin('Locality_layer','Locality_N') ")
f[fieldName] = e.evaluate()
layer.updateFeature(f)
But the values aren't updated in the table.
e = QgsExpression( "geomwithin('Locality_layer','Locality_N') ")– Joseph Aug 09 '19 at 13:01geomwithin('Locality_layer','Locality_N')in the field calculator? – Joseph Aug 09 '19 at 13:12