Skip to content

Instantly share code, notes, and snippets.

@NathanW2
Forked from mbernasocchi/gist:6726460
Last active December 24, 2015 01:50
Show Gist options
  • Save NathanW2/6726789 to your computer and use it in GitHub Desktop.
Save NathanW2/6726789 to your computer and use it in GitHub Desktop.
import os
import sys
import sip
from qgis.core import (
QgsApplication, QgsVectorLayer, QgsField,
QgsFields, QgsFeature, QgsGeometry, QgsPoint, QgsMapLayerRegistry)
from PyQt4.QtCore import QVariant
def main():
# setup QGIS
QgsApplication.initQgis()
catalogue_layer = QgsVectorLayer('Point?crs=epsg:4326', "catalogue", 'memory')
QgsMapLayerRegistry.instance().addMapLayer(catalogue_layer)
add_features(catalogue_layer)
# print list(catalogue_layer.getFeatures())
# print [f['cluster'] for f in catalogue_layer.getFeatures()]
# edit features
features = list(catalogue_layer.getFeatures())
catalogue_layer.startEditing()
# print features
for f in features:
f['cluster'] = 666.
print f, f['eventID']
catalogue_layer.updateFeature(f)
catalogue_layer.commitChanges()
print [(f['cluster'], f['eventID']) for f in features]
print [(f['cluster'], f['eventID']) for f in catalogue_layer.getFeatures()]
# Connect signal for app finish
QgsApplication.exitQgis()
sys.exit(0)
def add_features(vl):
pr = vl.dataProvider()
vl.startEditing()
data = {
'eventID': [0, 1, 2, 3, 4, 5],
'latitude': [0, 1, 2, 3, 4, 5],
'longitude': [0, 1, 2, 3, 4, 5],
'cluster': [0, 1, 2, 3, 4, 5]
}
fields = [QgsField(key, QVariant.Double) for key in data]
pr.addAttributes(fields)
features = []
qgs_fields = QgsFields()
map(qgs_fields.append, fields)
for i in range(6):
fet = QgsFeature(i)
fet.setFields(qgs_fields)
x = data['longitude'][i]
y = data['latitude'][i]
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(x, y)))
for key in data:
event_data = data[key]
fet[key] = event_data[i]
features.append(fet)
pr.addFeatures(features)
vl.commitChanges()
# print list(vl.getFeatures())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment