Sunday, 12 July 2015

PyQGIS update field in line dataset when it is within a polygon


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.



Answer



After ensuring you loaded your vector layer, you could use the following:


##Update LocalityName
e = QgsExpression( "geomwithin('Locality','Locality_N') ")
f[fieldName] = e.evaluate()
layer.updateFeature(f)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...