Buffers

You have mapped data from tables, but now you will map the results of a geoprocessing task—buffer.

To code a buffer example, we must first create a point. The following code will do that for us:

from shapely.geometry import mapping
p = Point([-106.578677,35.062485])
pgeojson=mapping(p)
player=GeoJSON(data=pgeojson)
map.add_layer(player)

The previous code creates a point using Shapely. It then converts it to GeoJSON using shapely.geometry.mapping(). The next two lines allow us to display it on the map.

PostGIS allows you to send data to the database and get data back, none of which has to be in a table. For example, examine the following code:

cursor.execute("SELECT ST_AsGeoJSON(ST_Buffer(ST_GeomFromText('{}')::geography,1500));".format(p.wkt))
buff=cursor.fetchall()
buffer=json.loads(buff[0][0])
bufferlayer=GeoJSON(data=buffer)
map.add_layer(bufferlayer)

The previous code uses ST_Buffer() to get a polygon back from PostGIS. ST_Buffer() can take a point geography and a radius in meters to return the polygon. The code wraps the result in ST_AsGeoJSON so we can map it. In this example, the result set is a single item, so we don't need the for loop. The code loads the result buff[0][0] and maps it.

The result of the previous code is shown in the following screenshot:

We now have a polygon that we can use to select incidents from. The following code will execute the same query as earlier, but instead of ST_AsGeoJSON, we will use ST_AsText. We are not mapping the polygon, but using it as a parameter for a point in the polygon operation:

cursor.execute("SELECT ST_AsText(ST_Buffer(ST_GeomFromText('{}')::geography,1500));".format(p.wkt))
bufferwkt=cursor.fetchall()
b=loads(bufferwkt[0][0])

In the previous code, the query result is passed to a shapely polygon named b using loads(). Now, you can pass that polygon to another query using ST_Intersects(), as in the following code:

cursor.execute("SELECT ST_AsGeoJSON(incidents.geom) FROM incidents where ST_Intersects(ST_GeomFromText('{}'), incidents.geom) and date >= NOW() - interval '10 day';".format(b.wkt))
crime=cursor.fetchall()
for x in crime:
layer=json.loads(x[0])
layergeojson=GeoJSON(data=layer)
map.add_layer(layergeojson)

The previous code selects the incidents as GeoJSON, where they intersect the buffer (b.wkt), and where they are within the last 10 days. The results are mapped. The following map shows the output of the previous code:

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

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