Loading layers

One of the first things you will probably need to do is load some existing GIS data. You can open several different file formats. The method for doing this is the same. It is done by creating a QgsVectorLayer and passing a parameter for the data source, the layer name to be shown in the layers panel widget, and the provider name as shown in the following code:

import requests 
import json
from qgis.core import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets
import *
from qgis.PyQt.QtCore import *

streets = QgsVectorLayer(r'C:UsersPaulDesktopPythonBookCHP8Streets.shp', "Streets","ogr")
scf = QgsVectorLayer(r'C:UsersPaulDesktopPythonBookCHP8SCF.shp', "SeeClickFix","ogr")

For most vector layers, you will use "ogr" as the provider. You can then add the layer to the map using the following code: 

QgsMapLayerRegistry.instance().addMapLayers([scf,streets]) 

The previous code adds the layer to the map registry. Alternatively, you can do the previously mentioned code in a single line of code using iface as shown in the following code:

streets = iface.addVectorLayer(r'C:UsersPaulDesktopPythonBookCHP8Streets.shp', "Streets","ogr") 
scf = iface.addVectorLayer(r'C:UsersPaulDesktopPythonBookCHP8SCF.shp', "SeeClickFix","ogr")

The previous code loads a vector layer and adds it to the registry in a single step. The following screenshot shows the layers added in QGIS and the names added to the layers panel:

A screenshot of the layers loaded in QGIS

The registry holds a list of all of the layers in the map document. You can get a list of loaded layers by using the following code:

QgsMapLayerRegistry.instance().mapLayers() 

The previous code should show that two layers, SeeClickFix and Streets, are loaded:

{u'SeeClickFix20171129100436571': <qgis._core.QgsVectorLayer object at 0x000000002257F8C8>, u'Streets20171129100433367': <qgis._core.QgsVectorLayer object at 0x000000002257F268>}

You can remove a layer from the map by using removeMapLayer() and passing the id of the layer to remove. The id is the string from the result of calling mapLayers(). In this case, the id of the loaded layer is 'Steets20171129092415901'. The following code will remove the layer:

QgsMapLayerRegistry.instance().removeMapLayer('Streets20171129100433367')

The previous code passes the layer id to removeMapLayer(). Since the data was loaded in the streets variable, you can also pass streets.id() instead of typing the layer id, as shown in the following code:

QgsMapLayerRegistry.instance().removeMapLayer(streets.id()) 

Both methods will result in the layer being removed from the map.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset