Geographic Information Systems Asked by raosaeedali on March 26, 2021
Is there a way to merge all the layers with same name using python script in QGIS in the following list;
names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]
print names
Output:
[u'Pois', u'Pois', u'Pois', u'Pois', u'Pois', u'Pois', u'Pois', u'Pois', u'Pois']
So that when I list my current mapLayers, all I get is one layer with all the other layers merged into it.
You can use processing algorithms :
import processing
processing.alghelp("qgis:mergevectorlayers")
pois_lyr_list = []
lyr_list = QgsMapLayerRegistry.instance().mapLayers()
for layer in lyr_list:
if layer.name() == u'Pois':
pois_lyr_list.append(layer)
processing.runandload("qgis:mergevectorlayers", pois_lyr_list, "memory:merged")
Correct answer by SYG on March 26, 2021
Here is an updated version for QGIS3. Note that I hardcoded CRS and result directory.
To get help for other CRS options you can run in Python Console:
import processing
processing.algorithmHelp('native:mergevectorlayers')
Merge layers with same name script:
import processing
grouped_layers_by_name = {}
distinct_layer_names = set()
project_layers = QgsProject.instance().layerTreeRoot().children()
for layer_item in project_layers:
layer_name = layer_item.name()
distinct_layer_names.add(layer_name)
grouped_layers_by_name[layer_name] = QgsProject.instance().mapLayersByName(layer_name);
print('Total number of distinct layers: ' + str(len(distinct_layer_names)))
for layer_name in distinct_layer_names:
print('Processing layer: ' + layer_name + '... ', end='')
merged_layer_file_name = 'D:/merged/' + layer_name + '.gpkg'
alg_params = {
'LAYERS': grouped_layers_by_name[layer_name],
'CRS': 'EPSG:3765',
'OUTPUT': merged_layer_file_name
}
result = processing.run('native:mergevectorlayers', alg_params)
print('done.')
print('All layers have been merged.')
Answered by phidrho on March 26, 2021
Simple version updated for QGIS3
import processing
listLayers = QgsProject.instance().mapLayersByName('Points')
processing.runAndLoadResults("native:mergevectorlayers",
{'LAYERS':listLayers,
'CRS':3006,
'OUTPUT':'TEMPORARY_OUTPUT'})
Answered by Slashy27 on March 26, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP