Drawing polygons from PostGIS

In this example, you will draw the Albuquerque Police Department Area Commands polygons from a PostGIS database. You will use the following code with an added PostGIS query, a loop to add all of the features, and a WKT function to draw the geometry instead of hard-coding the coordinates.

The first step is to connect to the PostGIS database. The following code is the same as you used in Chapter 3Introduction to Geospatial Databases, and Chapter 7Geoprocessing With Geodatabases:

 import psycopg2
connection =
psycopg2.connect(database="pythonspatial",user="postgres",
password="postgres")
cursor = connection.cursor()
cursor.execute("SELECT name, ST_AsTexT(geom) from areacommand")
c=cursor.fetchall()

The previous code connects to PostGIS, grabs all of the Area Commands with their name and geometry, and assigns them to the c variable. Next, you will create the layer as in the earlier example. You will create a counter x and make it the ID field of the features:

APD=QgsVectorLayer('Polygon?crs=epsg:4326','AreaCommands','memory') 
APDfeatures=APD.dataProvider()
APDfeatures.addAttributes([QgsField("ID",QVariant.Int),QgsField("Name", QVariant.String)])
x=0

The previous code creates a polygon memory layer, creates the features, and adds attributes. Next, you will look through the cursor, creating geometry for each Area Command and adding attributes, then you update the layer's extents and fields:

for acmd in c:
g=QgsGeometry()
g=QgsGeometry.fromWkt(acmd[1])
p=QgsFeature()
print(acmd[0])
p.setGeometry(g)
x+=1
p.setAttributes([x,str(acmd[0])])
APDfeatures.addFeatures([p])
APD.updateExtents()
APD.updateFields()

The previous code is the same as in the points example in the previous section. The one major difference is that you are creating the polygon using QgsGeometry.fromWkt(wkt). The acmd[1] variable is the WKT MultiPolygon string from PostGIS.

Lastly, add the layer to the map as in the following code:

QgsMapLayerRegistry.instance().addMapLayers([APD])

The following code will render the screenshot as follows:

And there you have it, the Area Command polygons for the Albuquerque Police Department as a layer in QGIS. Next, you will learn how to add, edit, and delete features from a layer.

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

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