Dalam contoh ini saya akan menggunakan dengan format shapefile. Anda bisa mengganti file shp dengan file anda sendiri. Berikut contoh kode programnya sebagai berikut:
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 09:36:42 2019
@author: Wawan H Nur
Mengkonversi file shp BatasKabupaten.shp ke database py_geo_db di PostgreSQL
"""
import subprocess
db_schema = "SCHEMA=geodata"
overwrite_option = "OVERWRITE=YES"
geom_type = "POLYGON"
output_format = "PostgreSQL"
db_connection = """PG:host=localhost port=5432 user=userwhn dbname=py_geo_db password=pwdwhn"""
input_shp = "../geodata/BatasKabupaten.shp"
subprocess.call(["ogr2ogr", "-lco", db_schema, "-lco", overwrite_option, "-nlt", geom_type, "-f", output_format, db_connection, input_shp])
Penjelasan dari kode program tersebut adalah melakukan konversi file shp dengan nama BatasKabupaten.shp yang mempunyai tipe geometri polygon kedalam geodatabase py_geo_db pada schema geodata. Kode skrip tersebut akan menghasilkan sebuah tabel BatasKabupaten di database py_geo_db pada schema geodata. Output format yang akan kita tuju PostgreSQL.
Untuk melihat layer hasil konversi dapat dilakukan dengan menggunakan QGIS.
Untuk tipe geometri terdapat beberapa format dengan contoh datanya sebagai berikut:
- POINT(0 0)
- LINESTRING(0 0,1 1,1 2)
- POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
- MULTIPOINT(0 0,1 2)
- MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
- MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
- GEOMETRYCOLLECTION(POINT(2 3),LINESTRING((2 3,3 4)))
shp2pgsql -g localhost -s 4532 -c -D -I D:/Virt/data/BatasKabupaten.shp geodata.BatasKabupaten | psql -U userwhn py_geo_db
Adapun bentuk umum kode konversi file shp diatas adalah:
shp2pgsql -g <host> -s <port> -c -D -I <lokasi file shp> <schema.tabel> | psql -U <user> <database>
Demikian tulisan singkat ini semoga bermanfaat dan akan dilanjutkan dengan bahasan selanjutnya, terima kasih. @wawanhn
Referensi:
https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html?highlight=shp#get-all-postgis-layers-in-a-postgresql-database
https://automating-gis-processes.github.io/CSC18/index.html
https://medium.com/@chrieke/essential-geospatial-python-libraries-5d82fcc38731
http://postgis.refractions.net/documentation/manual-1.3/ch04.html
0 comments:
Post a Comment