I am trying to make a memory layer in QGIS using python and then generate a grid base on calculations in meters. When I run the script, a banner comes and says the CRS is not defined. Then when I look at the derived information I see that the area of the Geometry and its position is wrong.
vector_layer = QgsVectorLayer('Polygon?crs:epsg=3879&field=ID:integer(3)&field=value:double','test',"memory")
poly = QgsGeometry.fromPolygonXY([[
QgsPointXY(34.18639744, 95.15668787),
QgsPointXY(12.0161471 , 82.35668787),
QgsPointXY(24.8161471 , 60.18643753),
QgsPointXY(46.98639744, 72.98643753)])
f = QgsFeature(vector_layer.fields())
f.setGeometry(poly)
vector_layer.dataProvider().addFeatures([f])
QgsProject.instance().addMapLayer(vector_layer)
This code will generate a square, but the location is wrong. I tried to define CRS afterward in the code:
crs = vector_layer.crs()
crs.createFromId(3879)
vector_layer.setCrs(crs)
QgsMapLayerRegistry.instance().addMapLayer(vector_layer)
But it did not work either. Can you please tell where I am making mistake?
1 Answer 1
As @Fran Raga said, you probably have a typo in your layer definition.
The reference system is set using ?crs=epsg:3879
and not ?crs:epsg=3879
.
Check the QGIS Python API | Class: QgsVectorLayer for more details:
crs=definition Defines the coordinate reference system to use for the layer. definition is any string accepted by
QgsCoordinateReferenceSystem.createFromString()
Change the syntax and try again, it should solve your problem.
Explore related questions
See similar questions with these tags.
QgsVectorLayeris
is not correct, the correct crs definition iscrs=EPSG:3879