Created
September 27, 2013 10:07
-
-
Save mbernasocchi/6726460 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import sip | |
for api in ['QString', 'QDate', 'QDateTime', 'QTextStream', | |
'QTime', 'QUrl', 'QVariant']: | |
sip.setapi(api, 2) | |
from qgis.core import ( | |
QgsApplication, QgsVectorLayer, QgsField, | |
QgsFields, QgsFeature, QgsGeometry, QgsPoint, QgsMapLayerRegistry) | |
from PyQt4.QtCore import QVariant | |
def main(): | |
# setup QGIS | |
QgsApplication.setPrefixPath(os.environ['QGIS_PREFIX_PATH'], True) | |
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.changeAttributeValue( | |
f['eventID'], | |
f.fieldNameIndex('cluster'), 666.) | |
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 = [] | |
for key in data: | |
fields.append(QgsField(key, QVariant.Double)) | |
pr.addAttributes(fields) | |
features = [] | |
qgs_fields = QgsFields() | |
for f in fields: | |
qgs_fields.append(f) | |
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
Why not