Monthly Archives: June 2014

pyQGIS manually copy all features with attributes from a layer into a memory layer [depricated – see new post]]


my_WkbType = { 'WKBUnknown': 0, 'WKBPoint':1, 'WKBLineString':2, 'WKBPolygon':3, 'WKBMultiPoint':4, 'WKBMultiLineString':5, 'WKBMultiPolygon':6, 'WKBNoGeometry':7, 'WKBPoint25D':8, 'WKBLineString25D':9, 'WKBPolygon25D':10, 'WKBMultiPoint25D':11, 'WKBMultiLineString25D':12, 'WKBMultiPolygon25D':13 }

my_rev_WkbType = {v:k for k, v in WKBType_enum.items()}

input_layer = QgsVectorLayer('path/to/input/file.shp', "input layer", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(input_layer)
QGisWKBType=input_layer.dataProvider().geometryType()
EPSG_code=int(dp.crs().authid().split(":")[1])

destination_layer=QgsVectorLayer(my_rev_WkbType[QGisWKBType]+'?crs=epsg:'+str(EPSG_code)+'&index=yes','memory layer','memory')
destination_layer_data_provider=destination_layer.dataProvider()

input_layer_attrib_names = input_layer.dataProvider().fields()

oldattributeList = input_layer.dataProvider().fields().toList()
newattributeList=[]
for attrib in oldattributeList:
  if destination_layer.fieldNameIndex(attrib.name())==-1:
    newattributeList.append(QgsField(attrib.name(),attrib.type()))
destination_layer_data_provider.addAttributes(newattributeList)
destination_layer.updateFields()

destination_layer.startEditing()
cfeature = QgsFeature()
cfeatures=[]
xfeatures = input_layer.getFeatures()
for xfeature in xfeatures:
  xgeometry = xfeature.geometry()
  cfeature_Attributes=[]
  cfeature_Attributes.extend(xfeature.attributes())
  cfeature.setGeometry(xgeometry)
  cfeature.setAttributes(cfeature_Attributes)
  cfeatures.append(cfeature)
destination_layer_data_provider.addFeatures(cfeatures)
destination_layer_data_provider.commitChanges()