官术网_书友最值得收藏!

Loading a vector layer from a spatial database

The PostGIS geodatabase is based on the open source Postgres database. The geodatabase provides powerful geospatial data management and operations. PyQGIS fully supports PostGIS as a data source. In this recipe, we'll add a layer from a PostGIS database.

Getting ready

Installing and configuring PostGIS is beyond the scope of this book, so we'll use a sample geospatial database interface from the excellent service www.QGISCloud.com. www.QGISCloud.com has its own Python plugin called QGIS Cloud. You can sign up for free and create your own geodatabase online by following the site's instructions, or you can use the example used in the recipe.

How to do it...

Perform the following steps to load a PostGIS layer into a QGIS map:

  1. First, create a new DataSourceURI instance:
    uri = QgsDataSourceURI()
    
  2. Next, create the database connection string:
    uri.setConnection("spacialdb.com", "9999", "lzmjzm_hwpqlf", "lzmjzm_hwpqlf", "0e9fcc39")
    
  3. Now, describe the data source:
    uri.setDataSource("public", "islands", "wkb_geometry", "")
    
  4. Then, create the layer:
    layer = QgsVectorLayer(uri.uri(), "Islands", "postgres")
    
  5. Just to be safe, make sure everything works:
    if not layer.isValid():
     print "Layer %s did not load" % layer.name()
    
  6. Finally, add the layer to the map if everything is okay:
    QgsMapLayerRegistry.instance().addMapLayers([layer])
    

You can see the islands layer in the map, as shown in the following screenshot:

How to do it...

How it works...

PyQGIS provides an object in the API to create a PostGIS data source in QgsDataSourceURI(). The connection string parameters in the second line of code are the database server, port, database name, user, and password. In the example, the database, username, and password are randomly generated unique names. The data source parameters are the schema name, table name, geometry column, and an optional SQL WHERE to subset the layer as needed.

主站蜘蛛池模板: 金山区| 浦北县| 茂名市| 文水县| 德令哈市| 定西市| 怀集县| 康保县| 应城市| 普兰店市| 丹东市| 怀化市| 集安市| 资源县| 台北县| 瑞金市| 武隆县| 克拉玛依市| 青浦区| 广饶县| 大方县| 罗城| 同江市| 济宁市| 平塘县| 景谷| 吉林省| 东阿县| 钟山县| 靖边县| 登封市| 东平县| 乌审旗| 文化| 曲麻莱县| 红河县| 潜江市| 滨州市| 通州区| 吉木乃县| 财经|