How to load a layer in QGIS using Python

In this task we will see how to load a layer in QGIS and add it to the map. All the operation are similar for both raster and vector layers.

The first operation is to select the Python Console from the Plugins menu:

console

Then, if you have to load a Vector layer:

# Load the layer
layer = QgsVectorLayer('path to the vector layer', 'display name', 'ogr')

# Add the layer to the map (comment the following line if the loading in the Layers Panel is not needed)
QgsMapLayerRegistry.instance().addMapLayer(layer)

If you have to load a Raster layer:

# Load the layer
layer = QgsRasterLayer('path to the raster layer', 'display name')

# Add the layer to the map (comment the following line if the loading in the Layers Panel is not needed)
QgsMapLayerRegistry.instance().addMapLayer(layer)

Note If you are working on a Python script, be sure to import the following row before anyone of the codes written above:

from qgis.core import *

The lines above represent only one of the several ways for loading a layer in QGIS. Let’s see more of them (they have different syntax, but lead to the same result!):

#1 Getting the currently active layer in the Layers Panel:

from qgis.utils import iface # not needed if you are running it from the Python Console

# Load the layer (for both vectors and rasters)
layer = iface.activeLayer()

#2 Getting the layer by its name

from qgis.core import * # not needed if you are running it from the Python Console
# Load the layer (for both vectors and rasters)
layer = QgsMapLayerRegistry.instance().mapLayersByName('name_of_the_loaded_layer')[0]

#3 Getting the layer using processing

import processing
# Load the layer (for both vectors and rasters)
layer = processing.getObject('path to the raster layer')
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s