Commonly adding or displaying geospatial data is the first step when starting working with GIS. Mainly there are two types of geospatial data format, vector and raster. Vector is stored in a coordinate or a list of coordinates in point, polyline or polygon geometry. Meanwhile the raster format storing the data in picture element (pixel).
This tutorial will discuss how to display vector data with python in QGIS. It will cover two methods to display vector data using QGIS interface and QGIS project instance. This tutorial is using QGIS 3.0.
Adding Vector Layer with QGIS Interface API
We are starting this tutorial with adding a vector layer in shp format using QGIS interface API. To add a vector layer with QGIS Interface API can be done with addVectorLayer method as in the following expression:
For example to add a street layer with the name public_streets.shp with ogr simple feature library will be:
Figure 1 shows the result when the expression was executed. The street data will be added into QGIS layer, and the data displayed in QGIS map canvas.
|Figure 1. Vector layer added to QGIS map canvas|
Adding Vector Layer with Project Instance
The second method we will use project instance to add vector data. For this we use the following syntax expression:
From the syntax above can be seen that we can use addMapLayer method to add a single layer or addMapLayers to add more than one layer in a list. Moreover we can also observe that the layer to be displayed must be defined as vector layer with QgsVectorLayer class. So firstly we have to define the layer using the class with the following syntax:
The listing code below shows the example of adding layer with this method.
Figure 2 shows the result of the code execution. Can be seen that those three layers have been added to the layer tree and displayed in QGIS map canvas.
|Figure 2. Adding vector layer with QGIS Project instance|
That's all the tutorial how to add vector layer with python in QGIS. Please see other tutorials which discuss other topics in this QGIS python programming tutorial series.