- QGIS Python Programming Cookbook
- Joel Lawhead
- 284字
- 2021-07-23 19:48:53
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:
- First, create a new
DataSourceURI
instance:uri = QgsDataSourceURI()
- Next, create the database connection string:
uri.setConnection("spacialdb.com", "9999", "lzmjzm_hwpqlf", "lzmjzm_hwpqlf", "0e9fcc39")
- Now, describe the data source:
uri.setDataSource("public", "islands", "wkb_geometry", "")
- Then, create the layer:
layer = QgsVectorLayer(uri.uri(), "Islands", "postgres")
- Just to be safe, make sure everything works:
if not layer.isValid(): print "Layer %s did not load" % layer.name()
- 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 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.
- 深入淺出Electron:原理、工程與實(shí)踐
- Oracle Database In-Memory(架構(gòu)與實(shí)踐)
- Visual FoxPro 程序設(shè)計(jì)
- JavaScript+jQuery開發(fā)實(shí)戰(zhàn)
- Banana Pi Cookbook
- 深入淺出React和Redux
- Orleans:構(gòu)建高性能分布式Actor服務(wù)
- 工業(yè)機(jī)器人離線編程
- MySQL數(shù)據(jù)庫應(yīng)用實(shí)戰(zhàn)教程(慕課版)
- Unreal Engine Game Development Cookbook
- 大話程序員:從入門到優(yōu)秀全攻略
- VB語言程序設(shè)計(jì)教程(第2版)
- Go語言從入門到進(jìn)階實(shí)戰(zhàn)(視頻教學(xué)版)
- Instant Buildroot
- Python Geospatial Analysis Cookbook