1

I've a KML file that contains several layers, if I use the usual method of adding vector layers from a file it only adds the first layer (the Point layer)

vlayer = QgsVectorLayer("C:\Users\HOME\Desktop\Test.kml", "Test", "ogr")

QgsMapLayerRegistry.instance().addMapLayer(vlayer)

How to add all the layers in this file?

enter image description here

2 Answers 2

2

To load a single kml:

fileName = "C:\Users\fran\Downloads\kml\KML_Samples.kml"
layer = QgsVectorLayer(fileName,"test","ogr")
subLayers =layer.dataProvider().subLayers()

for subLayer in subLayers:
    name = subLayer.split('!!::!!')[1]
    uri = "%s|layername=%s" % (fileName, name,)
    #Create layer
    sub_vlayer = QgsVectorLayer(uri, name, 'ogr')
    #Add layer to map
    QgsProject.instance().addMapLayer(sub_vlayer)

To load a folder with kml:

import os

path = r'C:\Users\fran\Downloads\kml'
for r, d, f in os.walk(path):
    for file in f:
        if '.kml' in file:
            fileName = os.path.join(r, file)
            layer = QgsVectorLayer(fileName,"test","ogr")
            subLayers =layer.dataProvider().subLayers()

            for subLayer in subLayers:
                name = subLayer.split('!!::!!')[1]
                uri = "%s|layername=%s" % (fileName, name,)
                #Create layer
                sub_vlayer = QgsVectorLayer(uri, name, 'ogr')
                #Add layer to map
                QgsProject.instance().addMapLayer(sub_vlayer)

Tested on QGIS 3.6

1

I followed the same steps explained in this question about GML .gz files and it worked.

iface.addVectorLayer on a gml file causes "Select vector layers to add" dialog (pyqgis)

1- Open one of the layers

2- Get its full URL iface.activeLayer().dataProvider().dataSourceUri()

3- Iterate through them

2
  • I know this post is from several months ago, but could you (or someone) expand on this solution please? I looked at the link but that's not clear either. They don't explain what exactly they are editing. 1 - open the layer how? 3- what do you mean by iterate through them? Jan 19, 2018 at 8:37
  • check this gis.stackexchange.com/a/322960/49538
    – Fran Raga
    May 16, 2019 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.