
# https://gis.stackexchange.com/questions/360828/how-to-use-qgscoordinatetransformcontext-to-export-vector-layer-to-another-crs
# 2023/'7/23


##########
# Test 1 #
##########
# This is a vector layer of point geometry and CRS set to EPSG:4326
input = iface.activeLayer()

context = QgsCoordinateTransformContext()
ref_crs = QgsCoordinateReferenceSystem("EPSG:4326")
dest_crs = QgsCoordinateReferenceSystem("EPSG:4258")
# According to the documentation, if the third element is void, it should use the default PROJ conversion string
context.addCoordinateOperation(ref_crs, dest_crs, "")

s_out = r"test_out_1.gpkg"
o_save_options = QgsVectorFileWriter.SaveVectorOptions()
o_save_options.layerName = lyr_airports.name()
tpl_err = QgsVectorFileWriter.writeAsVectorFormatV2(lyr_airports, s_out, context, o_save_options)
# The layer is written and I can load it in QGIS but it does not have information about CRS

##########
# Test 2 #
##########
# This is a vector layer of point geometry and CRS set to EPSG:4326
input = iface.activeLayer()

context = QgsCoordinateTransformContext()
ref_crs = QgsCoordinateReferenceSystem("EPSG:4326")
dest_crs = QgsCoordinateReferenceSystem("EPSG:4258")
# I obtained the PROJ string with the following command: projinfo -o PROJ -s EPSG:4326 -t EPSG:4258
context.addCoordinateOperation(ref_crs, dest_crs, "+proj=noop")

s_out = r"test_out_2.gpkg"
o_save_options = QgsVectorFileWriter.SaveVectorOptions()
o_save_options.layerName = lyr_airports.name()
tpl_err = QgsVectorFileWriter.writeAsVectorFormatV2(lyr_airports, s_out, context, o_save_options)
# The layer is written and I can load it in QGIS but it does not have information about CRS



# Solution

coordinateTransformContext=QgsProject.instance().transformContext()

o_save_options.ct = QgsCoordinateTransform(QgsCoordinateReferenceSystem( 'EPSG:4326') ,QgsCoordinateReferenceSystem('EPSG:3844'),coordinateTransformContext)

