#!/usr/bin/env python#-*-coding:utf-8-*-ImportPSYCOPG2ImportJSON fromGeojsonImportloads, Feature, featurecollection#Database Connection InfoDb_host ="localhost"Db_user="Pluto"db_passwd="stars"Db_database="PY_GEOAN_CB"Db_port="5432"#Connect to DBconn = Psycopg2.connect (Host=db_host, user=Db_user, Port=db_port, PASSWORD=DB_PASSWD, database=db_database)#Create a cursorCur =conn.cursor ()#The PostGIS buffer queryBuffer_query ="""SELECT St_asgeojson (St_transform (St_buffer (wkb_geometry, +, ' quad_segs=8 '), 4326)) as Geom, n Ame from Geodata.schools"""#Execute the queryCur.execute (buffer_query)#return all the rows, we expect more than oneDbrows =Cur.fetchall ()#An empty list for each feature of our feature collectionNew_geom_collection = []#loop through each row in result query set and add to my feature collection#Assign Name field to the GeoJSON properties forEach_polyinchDbrows:geom=Each_poly[0] Name= Each_poly[1] Geoj_geom=loads (geom) myfeat= Feature (Geometry=geoj_geom, properties={'name': Name}) New_geom_collection.append (myfeat)#Use the Geojson module to create the final Feature Collection of features created from A for loop aboveMy_geojson =featurecollection (new_geom_collection)#define the output folder and GeoJSon file nameOutput_geojson_buf =".. /geodata/out_buff_100m.geojson"#save Geojson to a file in our Geodata folderdefWrite_geojson (): Fo= Open (Output_geojson_buf,"W") Fo.write (Json.dumps (My_geojson)) Fo.close ()#run the Write function to actually create the GeoJSON fileWrite_geojson ()#Close Cursorcur.close ()#Close ConnectionConn.close ()
Convert PostGIS to Geojson