Carregando Camadas

Vamos abrir algumas camadas com dados. QGIS reconhece camadas vetoriais e matriciais. Adicionalmente, camadas personalizadas estão disponíveis, mas não discutiremos este tipo de camadas aqui.

Camadas Vetoriais

Para carregar uma camada vetorial, especifique o identificador da origem de dados, o nome da camada e o nome do provedor.

layer = QgsVectorLayer(data_source, layer_name, provider_name)
if not layer.isValid():
  print "Layer failed to load!"

O identificador da fonte de dados é uma string e é especifico para cada provedor de dados vetoriais. O nome da camada é usado no painel de lista de camadas. É importante verificar se a camada foi carregada com sucesso. Se não for, uma instância de camada inválida é retornada.

The quickest way to open and display a vector layer in QGIS is the addVectorLayer function of the QgisInterface:

layer = iface.addVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")
if not layer:
  print "Layer failed to load!"

This creates a new layer and adds it to the map layer registry (making it appear in the layer list) in one step. The function returns the layer instance or None if the layer couldn’t be loaded.

A lista a seguir mostra como acessar várias fontes de dados usando provedores de dados vetoriais:

  • OGR library (shapefiles and many other file formats) — data source is the path to the file

    vlayer = QgsVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")
    
  • PostGIS database — data source is a string with all information needed to create a connection to PostgreSQL database. QgsDataSourceURI class can generate this string for you. Note that QGIS has to be compiled with Postgres support, otherwise this provider isn’t available.

    uri = QgsDataSourceURI()
    # set host name, port, database name, username and password
    uri.setConnection("localhost", "5432", "dbname", "johny", "xxx")
    # set database schema, table name, geometry column and optionally
    # subset (WHERE clause)
    uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")
    
    vlayer = QgsVectorLayer(uri.uri(), "layer_name_you_like", "postgres")
    
  • CSV or other delimited text files — to open a file with a semicolon as a delimiter, with field “x” for x-coordinate and field “y” with y-coordinate you would use something like this

    uri = "/some/path/file.csv?delimiter=%s&xField=%s&yField=%s" % (";", "x", "y")
    vlayer = QgsVectorLayer(uri, "layer_name_you_like", "delimitedtext")
    

    Note: from QGIS version 1.7 the provider string is structured as a URL, so the path must be prefixed with file://. Also it allows WKT (well known text) formatted geometries as an alternative to “x” and “y” fields, and allows the coordinate reference system to be specified. For example

    uri = "file:///some/path/file.csv?delimiter=%s&crs=epsg:4723&wktField=%s" % (";", "shape")
    
  • GPX files — the “gpx” data provider reads tracks, routes and waypoints from gpx files. To open a file, the type (track/route/waypoint) needs to be specified as part of the url

    uri = "path/to/gpx/file.gpx?type=track"
    vlayer = QgsVectorLayer(uri, "layer_name_you_like", "gpx")
    
  • SpatiaLite database — supported from QGIS v1.1. Similarly to PostGIS databases, QgsDataSourceURI can be used for generation of data source identifier

    uri = QgsDataSourceURI()
    uri.setDatabase('/home/martin/test-2.3.sqlite')
    schema = ''
    table = 'Towns'
    geom_column = 'Geometry'
    uri.setDataSource(schema, table, geom_column)
    
    display_name = 'Towns'
    vlayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')
    
  • MySQL WKB-based geometries, through OGR — data source is the connection string to the table

    uri = "MySQL:dbname,host=localhost,port=3306,user=root,password=xxx|layername=my_table"
    vlayer = QgsVectorLayer( uri, "my_table", "ogr" )
    
  • WFS connection:. the connection is defined with a URI and using the WFS provider

    uri = "http://localhost:8080/geoserver/wfs?srsname=EPSG:23030&typename=union&version=1.0.0&request=GetFeature&service=WFS",
    vlayer = QgsVectorLayer("my_wfs_layer", "WFS")
    

    O URI pode ser criado usando a biblioteca urllib padrão.

    params = {
        'service': 'WFS',
        'version': '1.0.0',
        'request': 'GetFeature',
        'typename': 'union',
        'srsname': "EPSG:23030"
    }
    uri = 'http://localhost:8080/geoserver/wfs?' + urllib.unquote(urllib.urlencode(params))
    

Camadas Matriciais

For accessing raster files, GDAL library is used. It supports a wide range of file formats. In case you have troubles with opening some files, check whether your GDAL has support for the particular format (not all formats are available by default). To load a raster from a file, specify its file name and base name

fileName = "/path/to/raster/file.tif"
fileInfo = QFileInfo(fileName)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(fileName, baseName)
if not rlayer.isValid():
  print "Layer failed to load!"

Similarly to vector layers, raster layers can be loaded using the addRasterLayer function of the QgisInterface:

iface.addRasterLayer("/path/to/raster/file.tif", "layer_name_you_like")

Isto cria uma nova camada e adiciona ao registro de camadas do mapa (fazendo ele aparecer na lista de camadas) em um passo.

Camadas matriciais também podem ser criadas a partir de um serviço de WCS.

layer_name = 'modis'
uri = QgsDataSourceURI()
uri.setParam('url', 'http://demo.mapserver.org/cgi-bin/wcs')
uri.setParam("identifier", layer_name)
rlayer = QgsRasterLayer(str(uri.encodedUri()), 'my_wcs_layer', 'wcs')

detailed URI settings can be found in provider documentation

Alternatively you can load a raster layer from WMS server. However currently it’s not possible to access GetCapabilities response from API — you have to know what layers you want

urlWithParams = 'url=http://wms.jpl.nasa.gov/wms.cgi&layers=global_mosaic&styles=pseudo&format=image/jpeg&crs=EPSG:4326'
rlayer = QgsRasterLayer(urlWithParams, 'some layer name', 'wms')
if not rlayer.isValid():
  print "Layer failed to load!"

Registro de Camada de Mapa

Se você gostaria de usar as camadas abertas para renderização, não se esqueça de adicioná-los ao registro da camada de mapa. O registro camada de mapa apropria-se das camadas e podem ser mais tarde acessadas ​​a partir de qualquer parte do aplicativo pelo seu ID único. Quando a camada é removida do registro camada do mapa, ele é excluído, também.

Adiciona uma camada ao registro

QgsMapLayerRegistry.instance().addMapLayer(layer)

Layers are destroyed automatically on exit, however if you want to delete the layer explicitly, use

QgsMapLayerRegistry.instance().removeMapLayer(layer_id)

For a list of loaded layers and layer ids, use

QgsMapLayerRegistry.instance().mapLayers()
TODO:

Mais sobre o registro de camada e mapa?