16- Streamlining GeoPackage Layer Loading in PyQGIS with Custom Functions

In this article, we explain how to streamline GeoPackage layer loading in PyQGIS using custom functions. It provides examples of functions to add new layers, multiple layers, and all layers. It also includes a link to download sample data.

To get started, we need to download sample data in the GeoPackage format. We provide a link to download a GeoPackage file containing sample data. Once downloaded, we can unzip the file and load it into PyQGIS.

First, load a list of layer names in the GeoPackage:

from osgeo import ogr
gpkg1 = 'D:/Python_QGIS/data/osopentoid_202105_gpkg_sr/osopentoid_202105_sr.gpkg'
gpkg_layers = [n.GetName() for n in ogr.Open(gpkg1)]
print(gpkg_layers)
print('os_mastermap_topography_layer' in gpkg_layers)
# True
print('london_boroughs' in gpkg_layers)
# False (because the layer is not available)

Next, write a function to add new layers:

def add_layer(gpkg, layer):
    layers = [n.GetName() for n in ogr.Open(gpkg)]
    if layer in layers:
        iface.addVectorLayer(gpkg + "|layername=" + layer, layer, 'ogr')
    else:
        print('Error: there is no layer named "{}" in {}!'.format(layer, gpkg))

Use the defined add_layer function to add a new layer:

add_layer(gpkg1, 'os_mastermap_topography_layer')

Then, define a function to add multiple layers:

def add_layers(gpkg, layers):
    for layer in layers:
        add_layer(gpkg, layer)

# use add_layers function:
add_layers(gpkg1, ['os_mastermap_sites_layer', 'os_mastermap_highways_network'])

Finally, define a function to add all layers:

def add_all_layers(gpkg):
    layers = [n.GetName() for n in ogr.Open(gpkg)]
    add_layers(gpkg, layers)

 # use add_all_layers function:   
add_all_layers(gpkg1)

In conclusion, the article provides useful insights into how to streamline GeoPackage layer loading in PyQGIS using custom functions. It offers examples of functions to add new layers, multiple layers, and all layers. The article also includes a link to download sample data, which readers can use to practice the concepts discussed. Overall, this article is a valuable resource for anyone looking to improve their GeoPackage layer loading process in PyQGIS.

If you like the content, please SUBSCRIBE to my channel for the future content

Did you find this article valuable?

Support Azad Rasul by becoming a sponsor. Any amount is appreciated!