3

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?

asked Jun 9, 2019 at 11:24
1
  • 2
    your QgsVectorLayerisis not correct, the correct crs definition is crs=EPSG:3879 Commented Jun 9, 2019 at 11:28

1 Answer 1

3

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.

Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Jun 9, 2019 at 12:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.