Skip to content

Instantly share code, notes, and snippets.

@bsmithgall
Last active September 4, 2015 04:32
Show Gist options
  • Save bsmithgall/9285262 to your computer and use it in GitHub Desktop.
Save bsmithgall/9285262 to your computer and use it in GitHub Desktop.
Updating Feature Attributes in QGIS
# To avoid 'QVariant' is not defined error
from PyQt4.QtCore import *
import json
# Get all layers on the map's canvas
canvas = qgis.utils.iface.mapCanvas()
all_layers = canvas.layers()
# Make dictionary of election district features (individual
# districts) for inserting into spatial index
election_district = [i for i in all_layers if i.name() == 'election_district'][0]
all_ed_features = election_district.getFeatures()
# Make election district spatial index
ed_index = QgsSpatialIndex()
for f in all_ed_features:
ed_index.insertFeature(f)
# Now, create the parent layers, and set up geography for the
# intersection analysis
parent_layers = [i for i in all_layers if i.name() != 'election_district']
for layer in parent_layers:
# add the child ids as a new attribute
layer.dataProvider().addAttributes([
QgsField('ElectDist', QVariant.String)])
layer.updateFields()
# layer editing
layer.startEditing()
all_parent_features = layer.getFeatures()
for feature in all_parent_features:
# Get only the ids that intersect the proper election_district
ids = ed_index.intersects(feature.geometry().boundingBox())
str_ids = json.dumps(ids)
# Modify the election_districts attribute
feature['ElectDist'] = str_ids
layer.updateFeature(feature)
# commit to save the changes
layer.commitChanges()
# write the layer to an output geojson
QgsVectorFileWriter.writeAsVectorFormat(layer, '/Users/smithgall/Desktop/test_json.geojson', 'utf-8', None, 'GeoJSON')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment