4.4 Use H2GIS with Python - orbisgis/h2gis GitHub Wiki

Introduction

The following example demonstrates how to use H2GIS with the Python scripting language. The advantage is the ability to run it on dedicated server without X11.

Requirements:

  • To use H2GIS, you have to install Java from version 7.

Install H2GIS

To install H2GIS, follow this steps:

  • Download the latest H2GIS version on the home page, unzip it.
  • On Linux you can execute the following commands:
~ $ wget https://github.com/orbisgis/h2gis/releases/download/v1.3.2/h2gis-dist-1.3.2-bin.zip -O h2gis.zip
~ $ unzip h2gis.zip

Install psycopg2

http://initd.org/psycopg/docs/install.html#installation

Run H2GIS as a PosgreSQL sever mode

On Windows, Linux, Mac

java -cp "bin/*" org.h2.tools.Server -pg

Run Python script

python myscript.py

#!/usr/bin/python
from __future__ import print_function
import os


try:
    import psycopg2
except ImportError:
    print("Module psycopg2 is missing, cannot connect to PostgreSQL")
    exit(1)

def main():    
    #Define our connection string
    # db name has to be an absolute path
    db_name = (os.path.abspath(".")+os.sep+"mydb").replace(os.sep, "/")
    conn_string = "host='localhost' port=5435 dbname='"+db_name+"' user='sa' password='sa'"

    # print the connection string we will use to connect
    print("Connecting to database\n	->%s" % (conn_string))

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    print("Connected!\n")

    # Init spatial features
    cursor.execute("CREATE ALIAS IF NOT EXISTS H2GIS_SPATIAL FOR \"org.h2gis.functions.factory.H2GISFunctions.load\";")
    cursor.execute("CALL H2GIS_SPATIAL();")
    print("Spatial functions added!\n")

   # Add spatial table and query it
    cursor.execute("DROP TABLE IF EXISTS VANNES;")
    cursor.execute("CREATE TABLE VANNES (the_geom geometry, id int);")
    cursor.execute("INSERT INTO VANNES VALUES('POLYGON ((100 300, 210 300, 210 200, 100 200, 100 300))'::geometry, 1),('POINT (100 100)'::geometry, 2);")
    cursor.execute("SELECT * FROM VANNES;")
    print("Show me the table:\n")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
main()