레이어 읽기

Let’s open some layers with data. QGIS 는 벡터와 래스터 레이어를 인식합니다. 게다가 사용자 정의 레이어를 이용할 수 있지만 이 문서에서는 사용자 정의 레이어는 다루지 않습니다.

벡터 레이어

벡터 레이어를 읽기 위해 레이어의 데이터 소스 식별자, 이름, 프로바이더 이름를 지정하세요:

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

The data source identifier is a string and it is specific to each vector data provider. Layer’s name is used in the layer list widget. It is important to check whether the layer has been loaded successfully. If it was not, an invalid layer instance is returned.

The following list shows how to access various data sources using vector data providers:

  • 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 연결:: 연결은 WFS 프로바이더를 이용하여 URI와 함께 정의됩니다:

    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")
    

    URI는 표준 urllib 라이브러리를 이용하여 생성시킬 수 있습니다.

    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))
    

래스터 레이어

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!"

Raster layers can also be created from a WCS service.

layer_name = 'elevation'
uri = QgsDataSourceURI()
uri.setParam ('url', 'http://localhost:8080/geoserver/wcs')
uri.setParam ( "identifier", layer_name)
rlayer = QgsRasterLayer(uri, 'my_wcs_layer', 'wcs')

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!"

Map Layer Registry

If you would like to use the opened layers for rendering, do not forget to add them to map layer registry. The map layer registry takes ownership of layers and they can be later accessed from any part of the application by their unique ID. When the layer is removed from map layer registry, it gets deleted, too.

Adding a layer to the registry:

QgsMapLayerRegistry.instance().addMapLayer(layer)

QGIS가 종료되면 레이어는 자동으로 닫힙니다. 그러나 명백하게 레이어를 삭제하고 싶으면 다음을 이용하세요:

QgsMapLayerRegistry.instance().removeMapLayer(layer_id)
TODO:
More about map layer registry?