java+GDAL
0、环境配置
- 将proj.db所在路径添加到环境变量,变量名为
PROJ_LIB
2.编写代码
package com.lulie.gdal;
import org.gdal.gdal.gdal;
import org.gdal.ogr.ogr;
class GdalDemo {
public void printDriver() {
gdal.AllRegister();
int count = ogr.GetDriverCount();
for (int i = 0; i < count; i++) {
String driverName = ogr.GetDriver(i).getName();
System.out.print(driverName + "\t");
}
gdal.GDALDestroyDriverManager();
}
public static void main(String[] args) {
GdalDemo demo = new GdalDemo();
demo.printDriver();
}
}
结果:
注意:
遇到 ERROR 1: Can’t load requested DLL: E:\gdal\bin\gdal\plugins\gdal_GEOR.dll 错误,可以不管。
案例1-打开shp
package com.lulie.gdal;
import org.gdal.gdal.gdal;
import org.gdal.ogr.*;
public class GdalDemo_shp {
public String opeanShp(String strVectorFile) {
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
gdal.SetConfigOption("SHAPE_ENCODING","CP936");
String shpDriverName = "ESRI Shapefile";
Driver shpDriver =ogr.GetDriverByName(shpDriverName);
if (shpDriver == null) {
throw new RuntimeException(shpDriverName+ " 驱动不可用!\n");
}
DataSource shpDataSource = ogr.Open(strVectorFile,0);
if (shpDataSource == null)
{
throw new RuntimeException("打开文件【"+ strVectorFile + "】失败!" );
}
Layer shpLayer = shpDataSource.GetLayerByIndex(0);
if (shpLayer == null)
{
throw new RuntimeException("获取shp图层失败!\n");
}
Feature feature = shpLayer.GetNextFeature();
Geometry geometry = feature.GetGeometryRef();
String json = geometry.ExportToJson();
shpDataSource.delete();
gdal.GDALDestroyDriverManager();
return json;
}
public static void main(String[] args) {
GdalDemo_shp shp = new GdalDemo_shp();
String strVectorFile ="D:\\新建文件夹\\4496\\天府新区.shp";
String info = shp.opeanShp(strVectorFile);
System.out.println(info);
}
}
案例2-打开gdb
public void openGdb() {
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
gdal.SetConfigOption("SHAPE_ENCODING", "CP936");
String gdbDriverName = "FileGDB";
org.gdal.ogr.Driver gdbDriver = ogr.GetDriverByName(gdbDriverName);
if(gdbDriver == null){
System.out.println("不支持" + gdbDriverName + "驱动");
return;
}
String gdbPath = "C:\\Users\\lulie\\Desktop\\test.gdb";
DataSource gdbDataSource = gdbDriver.Open(gdbPath, 0);
if(gdbDataSource == null){
System.out.println("GDAL打开gdb失败!");
return;
}
for (int i = 0; i < gdbDataSource.GetLayerCount(); i++) {
String layerName = gdbDataSource.GetLayer(i).GetName();
System.out.println(layerName);
}
gdbDataSource.delete();
gdal.GDALDestroyDriverManager();
}
案例3-从pg库导出/导入shp
public static void pg2shp(){
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
gdal.SetConfigOption("SHAPE_ENCODING","CP936");
String pgDriverName = "PostgreSQL";
org.gdal.ogr.Driver pgDriver = ogr.GetDriverByName(pgDriverName);
if(pgDriver == null){
System.out.println("不支持" + pgDriverName + "驱动");
return;
}
String path = "PG:dbname=test host=localhost port=5432 user=postgres password=postgres";
DataSource pgDataSource = pgDriver.Open(path, 0);
if(pgDataSource == null){
System.out.println("GDAL连接PostGIS数据库失败!");
return;
}
String strSQL = "SELECT * from province WHERE area='测试'";
Layer pgLayer = pgDataSource.ExecuteSQL(strSQL);
if (pgLayer == null)
{
System.out.println("获取【" + "province" + "】图层失败!");
return;
}
System.out.println(pgLayer.GetFIDColumn());
String strVectorFile ="D:\\pg2shp.shp";
String shpDriverName = "ESRI Shapefile";
org.gdal.ogr.Driver shpDriver =ogr.GetDriverByName(shpDriverName);
if (shpDriver == null)
{
System.out.println(shpDriverName+ " 驱动不可用!\n");
return;
}
DataSource shpDataSource = shpDriver.CreateDataSource(strVectorFile,null);
if (shpDataSource == null)
{
System.out.println("创建矢量文件【"+ strVectorFile +"】失败!\n" );
return;
}
Layer shpLayer =shpDataSource.CreateLayer("", pgLayer.GetSpatialRef(), pgLayer.GetGeomType());
if (shpLayer == null)
{
System.out.println("图层创建失败!\n");
return;
}
FeatureDefn pgDefn =pgLayer.GetLayerDefn();
int iFieldCount =pgDefn.GetFieldCount();
for (int i = 0; i <iFieldCount; i++)
{
FieldDefn oField =pgDefn.GetFieldDefn(i);
shpLayer.CreateField(oField, 1);
}
Feature oFeature = null;
while ((oFeature = pgLayer.GetNextFeature()) != null)
{
System.out.println(oFeature.GetFID());
shpLayer.CreateFeature(oFeature);
}
shpLayer.SyncToDisk();
shpDataSource.SyncToDisk();
pgDataSource.delete();
shpDataSource.delete();
gdal.GDALDestroyDriverManager();
System.out.println("shp文件创建成功!");
}
public static void shp2pg(){
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
gdal.SetConfigOption("SHAPE_ENCODING","CP936");
String shpDriverName = "ESRI Shapefile";
org.gdal.ogr.Driver shpDriver =ogr.GetDriverByName(shpDriverName);
if (shpDriver == null)
{
System.out.println(shpDriverName+ " 驱动不可用!\n");
return;
}
String strVectorFile ="D:\\pg2shp.shp";
DataSource shpDataSource = ogr.Open(strVectorFile,0);
if (shpDataSource == null)
{
System.out.println("打开文件【"+ strVectorFile + "】失败!" );
return;
}
Layer shpLayer = shpDataSource.GetLayerByIndex(0);
if (shpLayer == null)
{
System.out.println("获取shp图层失败!\n");
return;
}
System.out.println(shpLayer.GetFIDColumn());
String pgDriverName = "PostgreSQL";
org.gdal.ogr.Driver pgDriver = ogr.GetDriverByName(pgDriverName);
if(pgDriver == null){
System.out.println("不支持" + pgDriverName + "驱动");
return;
}
String path = "PG:dbname=test host=localhost port=5432 user=postgres password=postgres";
DataSource pgDataSource = pgDriver.Open(path, 1);
if(pgDataSource == null){
System.out.println("GDAL连接PostGIS数据库失败!");
return;
}
Layer pgLayer = pgDataSource.GetLayerByName("tablename");
if (pgLayer == null)
{
System.out.println("获取【" + "tablename" + "】图层失败!");
return;
}
Feature oFeature = null;
while ((oFeature = shpLayer.GetNextFeature()) != null)
{
oFeature.SetFID(100 + oFeature.GetFID());
System.out.println(oFeature.GetFID());
pgLayer.CreateFeature(oFeature);
}
pgLayer.SyncToDisk();
pgDataSource.SyncToDisk();
pgDataSource.delete();
shpDataSource.delete();
gdal.GDALDestroyDriverManager();
System.out.println("shp文件导入成功!");
}
案例4-读取属性
public void readAttribute() {
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
gdal.SetConfigOption("SHAPE_ENCODING", "CP936");
String gdbDriverName = "FileGDB";
org.gdal.ogr.Driver gdbDriver = ogr.GetDriverByName(gdbDriverName);
if(gdbDriver == null){
System.out.println("不支持" + gdbDriverName + "驱动");
return;
}
String gdbPath = "C:\\Users\\lulie\\Desktop\\test.gdb";
DataSource gdbDataSource = gdbDriver.Open(gdbPath, 0);
if(gdbDataSource == null){
System.out.println("GDAL连接GDB失败!");
return;
}
for (int i = 0; i < gdbDataSource.GetLayerCount(); i++) {
Layer layer = gdbDataSource.GetLayer(i);
System.out.println(" layerName :" + layer.GetName());
List<String> fieldNames = new ArrayList<String>();
FeatureDefn featureDefn = layer.GetLayerDefn();
for (int i1 = 0; i1 < featureDefn.GetFieldCount(); i1++) {
FieldDefn fieldDefn = featureDefn.GetFieldDefn(i1);
String fields = fieldDefn.GetName();
fieldNames.add(fields);
}
System.out.println("所有字段名:" + fieldNames);
Feature feature = null;
while ((feature = layer.GetNextFeature()) != null) {
List<String> fieldValue = new ArrayList<String>();
String geojson = feature.GetGeometryRef().ExportToJson();
System.out.println("geojson :" + geojson);
for (String fieldName : fieldNames) {
String field = feature.GetFieldAsString(fieldName);
fieldValue.add(field);
}
System.out.println(fieldValue);
}
}
gdbDataSource.delete();
gdal.GDALDestroyDriverManager();
}
1、连接数据源
1.1、连接之前
gdal.AllRegister();
ogr.RegisterAll();
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
gdal.SetConfigOption("SHAPE_ENCODING", "CP936");
1.2、数据源驱动
public class DriverName {
public static final String shp = "ESRI Shapefile";
public static final String gdb = "FileGDB";
public static final String postgreSQL = "PostgreSQL";
public static final String sde = "OCI";
public static final String mdb = "PGeo";
}
1.3、连接数据源的基本过程
1、根据驱动名称获取驱动
Driver driver = ogr.GetDriverByName(driverName);
2、通过驱动打开数据源
DataSource dataSource = driver.Open(FilePath, 0);
3、获取数据源里的图层
dataSource.GetLayer(index:)
dataSource.GetLayer(layerName:"")
4、获取图层里的要素
layer.GetFeature(int:);
layer.ResetReading();
layer.GetNextFeature();
1.4、读取数据基本信息
读取图层数量:
int layerCount = dataSource.GetLayerCount();
图层名称
String layerName = layer.GetName();
图层要素数量
long featureCount = layer.GetFeatureCount();
图层空间参考信息
SpatialReference s = layer.GetSpatialRef();
图层的属性表结构
FeatureDefn featureDefn = layer.GetLayerDefn();
属性表字段数量
int fieldCount = featureDefn.GetFieldCount();
属性表的属性字段
FieldDefn fieldDefn = featureDefn.GetFieldDefn(i1);
属性字段类型
int fieldType = fieldDefn.GetFieldType();
String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType);
属性字段名称
String fieldName = fieldDefn.GetName();
获取FID
long fid = feature.GetFID();
获取Geometry
Geometry geometry = feature.GetGeometryRef();
String geoJson = geometry.ExportToJson();
{ "type": "Polygon", "coordinates": [ [ [ 119.456586303, 32.063698523000028, 0.0 ], [ 119.468721554000012, 32.045852565000018, 0.0 ], [ 119.490850540999986, 32.040141859000016, 0.0 ], [ 119.472290745, 32.028006608, 0.0 ], [ 119.478001451999944, 32.003736104999973, 0.0 ], [ 119.457300141000019, 32.023723577999988, 0.0 ], [ 119.43659882999998, 32.002308428999982, 0.0 ], [ 119.443023375000053, 32.025865093, 0.0 ], [ 119.422322064000014, 32.034431152000025, 0.0 ], [ 119.445878728000025, 32.043711050000013, 0.0 ], [ 119.456586303, 32.063698523000028, 0.0 ] ] ] }
获取图层范围
double[] extent = layer.GetExtent();
2、关于投影
SpatialReference spatialReference = layer.GetSpatialRef();
SpatialReference spatialReference = new SpatialReference();
spatialReference.ImportFromEPSG(4490);
String strwkt = "GEOGCS[\"GCS_North_American_1927\"," +
"DATUM[\"North_American_Datum_1927\"," +
"SPHEROID[\"Clarke_1866\",6378206.4,294.9786982]]," +
"PRIMEM[\"Greenwich\",0]," +
"UNIT[\"Degree\",0.0174532925199433]]";
SpatialReference spatialReference = new SpatialReference(strwkt);
投影信息如下(WKT字符串):
PROJCS[“CGCS2000 / 3-degree Gauss-Kruger CM 117E”, //投影名称 GEOGCS[“China Geodetic Coordinate System 2000”, //地理坐标系名称 DATUM[“China_2000”, //水平基准面 SPHEROID[“CGCS2000”,6378137,298.257222101,//椭球体、长半轴,反偏率 AUTHORITY[“EPSG”,“1024”]], AUTHORITY[“EPSG”,“1043”]], PRIMEM[“Greenwich”,0, //中央经线Greenwich,0度标准子午线 AUTHORITY[“EPSG”,“8901”]], UNIT[“degree”,0.0174532925199433, //指定测量使用的单位。在地理坐标系下使用角度。 AUTHORITY[“EPSG”,“9122”]], AUTHORITY[“EPSG”,“4490”]], PROJECTION[“Transverse_Mercator”], //投影方式 PARAMETER[“latitude_of_origin”,0], //PARAMETER表示投影参数,0表示纬度起点为0度 PARAMETER[“central_meridian”,117], //投影带的中央经线是东经117度 PARAMETER[“scale_factor”,1], //中央经线的长度比是1 PARAMETER[“false_easting”,500000], //坐标纵轴向西移动500km PARAMETER[“false_northing”,0], //横轴没有平移 UNIT[“metre”,1, //指定测量使用的单位,指定米为测量单位 AUTHORITY[“EPSG”,“9001”]], AXIS[“Northing”,NORTH], AXIS[“Easting”,EAST], AUTHORITY[“EPSG”,“4548”]]
3、属性查询
3.1 通过图层layer查询
int result = layer.SetAttributeFilter("YSDM='3002020100'");
layer.SetAttributeFilter(null);
3.2 通过数据源datasource查询
Layer queryLayer = dataSource.ExecuteSQL("select * from union5 where YSDM='3002020100'");
4、地理处理
public static void spatialQuery(Layer inputLayer,Layer queryLayer,Layer resultLayer,int spatialFilter){
Vector v = new Vector(4);
v.add("SKIP_FAILURES=YES");
v.add("PROMOTE_TO_MULTI=NO");
v.add("INPUT_PREFIX=1_");
v.add("METHOD_PREFIX=2_");
switch (spatialFilter){
case 0:
inputLayer.Intersection(queryLayer,resultLayer,v,null);
break;
case 1:
inputLayer.Union(queryLayer,resultLayer,v,null);
}
}
5、创建图层
public static Layer createLayer(String driverName, String path, String layerName, SpatialReference spatialReference) {
Layer result = null;
Driver driver = ogr.GetDriverByName(driverName);
if (driver == null) {
log.info(driverName + "不可用");
System.out.println(driverName + "不可用");
return null;
}
DataSource dataSource = null;
File file = new File(path);
if (file.exists()) {
if (file.isFile()) {
file.delete();
dataSource = driver.CreateDataSource(path, null);
} else if (file.isDirectory()) {
dataSource = driver.Open(path, 1);
for (int i = 0; i < dataSource.GetLayerCount(); i++) {
Layer layer = dataSource.GetLayer(i);
if (layerName.equals(layer.GetName())) {
dataSource.DeleteLayer(i);
dataSource.FlushCache();
}
}
}
} else {
dataSource = driver.CreateDataSource(path, null);
}
if (dataSource == null) {
log.info("数据源创建/打开失败");
System.out.println("数据源创建/打开失败");
return null;
}
result = dataSource.CreateLayer(layerName, spatialReference, ogr.wkbPolygon, null);
if (result == null) {
log.info(layerName + "创建失败");
System.out.println(layerName + "创建失败");
return null;
}
log.info("【"+layerName+"】" + "创建成功");
return result;
}
6、创建要素
public static void createFeatureByGeometry(Layer layer, Geometry geometry) {
FeatureDefn featureDefn = layer.GetLayerDefn();
Feature feature = new Feature(featureDefn);
feature.SetGeometry(geometry);
layer.CreateFeature(feature);
}
r(layerName, spatialReference, ogr.wkbPolygon, null); if (result == null) { log.info(layerName + “创建失败”); System.out.println(layerName + “创建失败”); return null; } log.info("【"+layerName+"】" + “创建成功”); return result; }
## 6、创建要素
```java
/**
* 传入Geometry创建Feature,这里不定义属性字段
* @param layer
* @param geometry
*/
public static void createFeatureByGeometry(Layer layer, Geometry geometry) {
FeatureDefn featureDefn = layer.GetLayerDefn();
Feature feature = new Feature(featureDefn);
feature.SetGeometry(geometry);
layer.CreateFeature(feature);
}
|