[Qgis-developer] Add Attributes, Features and Geometries to QgsVectorFileWriter
Josua Stähli
josh-talk at hotmail.com
Fri Mar 21 17:09:42 PDT 2014
Hello
My goal is to write some features and geometries to a JSON file. I searched for examples however in QGIS 2 (I am using 2.2) something seems to have changed so it does not work. Here is a very simple example of what I want to do:
fields = QgsFields()fields.append(QgsField("name"))fields.append(QgsField("description"))writer = QgsVectorFileWriter("/path/to/file.geojson", "utf-8", fields, QGis.WKBPoint, None, "GeoJSON")feature = QgsFeature(fields)feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(1, 2)))feature.setAttributes(["name", "xyz"])writer.addFeature(newFeature)del writer
The result is a JSON file with the following content:
{"type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { }, "geometry": null }]}
So the feature is added but attributes and geometry are ignored. Do you have any idea what I am doing wrong? I also tried to create a memory layer:
layer = QgsVectorLayer("Point", "temp", "memory")provider = layer.dataProvider()layer.startEditing()provider.addAttributes([QgsField("name"), QgsField("description")])feature = QgsFeature(fields)feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(1, 2)))feature.setAttributes(["namex", "xyz"])provider.addFeatures([feature])layer.updateFields()QgsVectorFileWriter.writeAsVectorFormat(layer, "/path/to/file.geojson", "utf-8", None, "GeoJSON")
The result looks a little bit better:
{"type": "FeatureCollection","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::21781" } }, "features": [{ "type": "Feature", "properties": { }, "geometry": { "type": "Point", "coordinates": [ 1.0, 2.0 ] } }]}
But the attributes are still missing. Does anybody know how this is done correctly? Thank you very much!
Josua
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20140322/bd8398a4/attachment.html>
More information about the Qgis-developer
mailing list