4

So I have one layerA with CRS:4326 and I can change CRS saving it:

# This layer has crs:4346
layerA = QgsVectorLayer("layerA.sqlite", "layerA", "ogr")

#New crs
crs=QgsCoordinateReferenceSystem("epsg:32629")

#saving layerA to layerB with new crs:32629
error = QgsVectorFileWriter.writeAsVectorFormat(layerA, "layerB.sqlite", "UTF-8", crs , "SpatiaLite")

With this code I can get a new LayerB with another CRS

I have read this: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/crs

But I think this solution need to iterating over every feature to reproject it.

Is there any solution to reproject a layer with only one instruction (like when saving it) but without need to create a new layer ?

Something like layerA.reproject(newCRS) ?

7

I don't think you can reproject a layer and overwrite its data at the same time it is being accessed. One option is to:

  1. Create a memory layer
  2. Transfer all data from the original layer to the memory layer
  3. Remove any dependencies on the original layer
  4. Overwrite original layer with the new CRS

# Get original shapefile and its features
layer = QgsVectorLayer("path/to/shapefile", "polygon", "ogr")
feats = [feat for feat in layer.getFeatures()]

# Create memory layer and copy over all attributes and geometries
mem_layer = QgsVectorLayer("Polygon?crs=epsg:4326", "memory_layer", "memory")
mem_layer_data = mem_layer.dataProvider()
attr = layer.dataProvider().fields().toList()
mem_layer_data.addAttributes(attr)
mem_layer.updateFields()
mem_layer_data.addFeatures(feats)
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

# Get original shapefile path
layer_source = layer.source()
# Remove dependence on shapefile
del layer
#New crs
crs = QgsCoordinateReferenceSystem("EPSG:32629")
# Overwrite original shapefile
error = QgsVectorFileWriter.writeAsVectorFormat(mem_layer, layer_source, "utf-8", crs, "ESRI Shapefile")
# Add result to canvas
QgsMapLayerRegistry.instance().addMapLayer(QgsVectorLayer(layer_source, "Result", "ogr"))
  • Thanks, Joseph. There is not a clean solution, maybe only save it to with another crs and reload (that is the more clean, I think), because calling to algorhtim docs.qgis.org/2.6/en/docs/user_manual/processing_algs/qgis/… need create a progress bar object before call it from standalone script. – Juanma Font Dec 15 '16 at 11:15
  • 1
    @JuanmaFont - I agree that saving it to another shapefile is cleaner (especially easier using the Reproject algorithm) but in response to your question, the above code is what I have used :) – Joseph Dec 15 '16 at 11:19

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.