2

I came up with the following issue in PyQGIS (2.8.9-Wien on Windows) when trying to save a created point to a vector file: the point was saved as (inf,inf) in the vector file if the coordinates in Lambert 72 were used with the EPSG code 31370 to create the crs. The point was properly saved when using WGS84 and the respective EPSG code 4326. See code example below.

# create a point and add to project
v_path = r'C:\tmp\test.shp'
crs_epsg = 31370
pt = (161000, 224000)
nlayer = QgsVectorLayer("Point", "poi", "memory")
pr = nlayer.dataProvider()
# add fields and update vector layer
pr.addAttributes([QgsField("name", QVariant.String)])
nlayer.updateFields()
# add a feature
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt[0], pt[1])))
fet.setAttributes(["poi"])
pr.addFeatures([fet])
# Commit changes
nlayer.updateExtents()

# create the crs
crs = QgsCoordinateReferenceSystem()
crs.createFromId(crs_epsg, QgsCoordinateReferenceSystem.EpsgCrsId)
print crs.isValid()

# save to vector file
_writer = QgsVectorFileWriter.writeAsVectorFormat(nlayer, v_path, 'system', crs, "ESRI Shapefile")
del _writer
del nlayer

# load created vector file and check feature
nlayer = QgsVectorLayer(v_path, 'poi', "ogr")
f = QgsFeature()
features = nlayer.getFeatures()
for f in features:
    print "F:", f.id(), f.attributes(), f.geometry().asPoint()

This returns the following output:

True
F: 0 [u'poi'] (inf,inf)

But with pt = (4.52656, 51.3257) and crs_epsg = 4326 it works fine?

True
F: 0 [u'poi'] (4.52656,51.3257)

The solution for me could be easy (converting the points to WGS84 before saving).

Can anyone could point me to the error in my code?

1

When creating your memory layer, you should define the CRS of the layer at the same time. If you replace:

nlayer = QgsVectorLayer("Point", "poi", "memory")

with this:

nlayer = QgsVectorLayer("Point?crs=epsg:31370", "poi", "memory")

your final line in your code should print:

F: 0 [u'poi'] (161000,224000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.