Gdal访问Postgresql中的矢量数据
目录
前言
Gdal功能非常强大,不仅可以访问shp、tif等保存在本地的空间数据,还支持访问保存在空间数据库中的空间数据。通过Gdal访问保存在Postgresql中的矢量数据和栅格数据略有差别,本文暂不介绍如何访问栅格数据,只介绍如何访问矢量数据。OK,下面我们来具体看下如何用Gdal访问保存在Postgresql中的矢量数据。
1、编译Gdal支持Postgresql驱动
默认编译的Gdal是不支持Postgresql驱动的,要通过Gdal访问保存在Postgresql中的矢量数据,必须重新编译Gdal使其支持Postgresql驱动,如果不知道该如何做,可查看这里。
2、访问Postgresql中的矢量数据
本文先将一个名为test1的shp文件导入到postgresql中,然后利用Gdal访问Postgresql,读取了该数据的字段信息以及第一条记录的所有属性值,并进行了输出,具体代码如下:
import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Feature;
import org.gdal.ogr.FeatureDefn;
import org.gdal.ogr.FieldDefn;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
public class HelloGDAL {
public static void readVectorSpacial(){
DataSource dataSource = null;
try{
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
gdal.SetConfigOption("SHAPE_ENCODING","CP936");
String driverName = "PostgreSQL";
org.gdal.ogr.Driver driver = ogr.GetDriverByName(driverName);
String path = "PG:dbname=Test host=localhost port=5432 user=postgres password=postgres";
dataSource = driver.Open(path, 0);
Layer vectorLayer = dataSource.GetLayerByName("test1");
FeatureDefn oDefn =vectorLayer.GetLayerDefn();
int fieldCount =oDefn.GetFieldCount();
System.out.println(fieldCount);
for (int i = 0; i < fieldCount; i++)
{
FieldDefn oField =oDefn.GetFieldDefn(i);
System.out.println(oField.GetNameRef()+ ": "
+ oField.GetFieldTypeName(oField.GetFieldType())
+ "(" + oField.GetWidth()+"."+ oField.GetPrecision() + ")");
}
Feature oFeature = null;
while ((oFeature = vectorLayer.GetNextFeature()) != null)
{
for (int i = 0; i< fieldCount; i++)
{
FieldDefn oFieldDefn= oDefn.GetFieldDefn(i);
int type =oFieldDefn.GetFieldType();
switch (type)
{
case ogr.OFTString:
System.out.println(oFeature.GetFieldAsString(i)+ "\t");
break;
case ogr.OFTReal:
System.out.println(oFeature.GetFieldAsDouble(i)+ "\t");
break;
case ogr.OFTInteger:
System.out.println(oFeature.GetFieldAsInteger(i)+ "\t");
break;
default:
System.out.println(oFeature.GetFieldAsString(i)+ "\t");
break;
}
}
Geometry oGeometry =oFeature.GetGeometryRef();
String geomWKT = oGeometry.ExportToWkt();
System.out.println(geomWKT);
// 演示,只输出一个要素信息
break;
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(dataSource != null){
dataSource.delete();
}
gdal.GDALDestroyDriverManager();
}
}
public static void main(String[] args) {
readVectorSpacial();
}
}
3、输出结果
参考文献
https://blog.csdn.net/n_sev7/article/details/46986059
https://www.gdal.org/drv_pg.html
转载自:https://blog.csdn.net/qq_24309981/article/details/84147138