Opengis utils for java

From znlgis/opengis-skills · View interactive version

Opengis utils for java is an AI agent skill from the GitHub repository znlgis/opengis-skills. Use when needing common GIS utilities in Java — OguLayerUtil layer read/write, GeometryUtil 60+ ops, CrsUtil CGCS2000 (EPSG:4490, 4502-4554), Shapefile/GeoJSON/FileGDB/PostGIS/land TXT I/O, topology validation; also for GDAL UnsatisfiedLinkError on gdal_jni, missing osgeo repo on GeoTools, or resolv

How to use this skill

Skill file

项目地址: <https://github.com/znlgis/opengis-utils-for-java>

官方文档: <https://github.com/znlgis/opengis-utils-for-java#readme>

最新版本: 1.0.0(截至 2026-11,仓库 CODE0 分支 CODE1,无 Git tag;尚未发布到 Maven Central,需从源码 mvn install 安装到本地仓库)

Maven 坐标: com.znlgis.ogu4j:ogu4j

许可证: LGPL-2.1-or-later

概述

OGU4J (OpenGIS Utils for Java) is a unified Java GIS toolkit built on GeoTools, JTS, GDAL/OGR, and ESRI Geometry API. It provides:

Java Version: 17+

Build Tool: Maven

Group ID: com.znlgis.ogu4j | Artifact ID: ogu4j | Version: 1.0.0


环境准备

# 前置:JDK 17+ 与 Maven 3.8+
java -version
mvn -version

# 克隆并构建(安装到本地 Maven 仓库)
git clone https://github.com/znlgis/opengis-utils-for-java.git
cd opengis-utils-for-java
mvn install -DskipTests

在业务项目的 pom.xml 中引入依赖(GeoTools 依赖通过 osgeo 仓库解析):

<repositories>
    <repository>
        <id>osgeo</id>
        <url>https://repo.osgeo.org/repository/release/</url>
    </repository>
</repositories>

<dependency>
    <groupId>com.znlgis.ogu4j</groupId>
    <artifactId>ogu4j</artifactId>
    <version>1.0.0</version>
</dependency>

环境要求: JDK 17+;GDAL 引擎需本地原生 GDAL 库(与 org.gdal:gdal 绑定版本 3.13.0 匹配);纯 GeoTools 引擎无需原生库。验证:mvn dependency:tree 中出现 com.znlgis.ogu4j:ogu4j:1.0.0,且代码中 import com.znlgis.ogu4j.datasource.OguLayerUtil; 可编译。


核心 API:包结构与入口类

com.znlgis.ogu4j
├── datasource/                  # High-level data I/O
│   ├── OguLayerUtil             # Primary entry point for reading/writing layers
│   └── GtTxtUtil                # National land TXT format support
├── engine/                      # GIS engine core
│   ├── GisEngine                # Engine interface
│   ├── GisEngineFactory         # Engine factory (auto-selects best engine)
│   ├── GeoToolsEngine           # GeoTools implementation (pure Java, always available)
│   ├── GdalEngine               # GDAL implementation (requires native GDAL)
│   ├── GeoToolsLayerReader/Writer  # GeoTools format I/O
│   ├── GdalLayerReader/Writer      # GDAL format I/O
│   ├── enums/                   # Enumerations
│   │   ├── DataFormatType       # SHP, GEOJSON, FILEGDB, POSTGIS, TXT, WKT, ESRIJSON, ARCSDE
│   │   ├── FieldDataType        # INTEGER, DOUBLE, STRING, BINARY, DATE, TIME, DATETIME, LONG
│   │   ├── GeometryType         # POINT, MULTIPOINT, LINESTRING, POLYGON, etc.
│   │   ├── GisEngineType        # GEOTOOLS, GDAL, AUTO
│   │   └── TopologyValidationErrorType
│   ├── io/                      # Reader/Writer interfaces
│   │   ├── LayerReader          # read(path, layerName, attributeFilter, spatialFilterWkt)
│   │   └── LayerWriter          # write(layer, path, layerName, options)
│   ├── model/
│   │   ├── layer/               # Core data model
│   │   │   ├── OguLayer         # Layer: name, wkid, geometryType, fields, features
│   │   │   ├── OguFeature       # Feature: id, geometry (WKT), attributes
│   │   │   ├── OguField         # Field definition: name, alias, dataType, length
│   │   │   ├── OguFieldValue    # Field value with type conversion methods
│   │   │   ├── OguCoordinate    # Coordinate point (x, y, z)
│   │   │   ├── OguFeatureFilter # Functional interface for filtering
│   │   │   └── OguLayerMetadata # Extended metadata (CRS, projection, etc.)
│   │   ├── DbConnBaseModel      # PostGIS connection configuration
│   │   ├── GdbGroupModel        # FileGDB structure
│   │   ├── TopologyValidationResult
│   │   └── SimpleGeometryResult
│   └── util/
│       ├── CrsUtil              # Coordinate system management & transformation
│       ├── GeotoolsUtil         # GeoTools feature filtering
│       ├── OgrUtil              # GDAL/OGR initialization & resource management
│       ├── PostgisUtil          # PostGIS connection helpers
│       ├── ShpUtil              # Shapefile encoding & field name handling
│       └── GdalCmdUtil          # GDAL command-line wrapper (ogrinfo)
├── geometry/
│   └── GeometryUtil             # 60+ geometry operation methods
├── exception/
│   ├── OguException             # Base checked exception
│   ├── DataSourceException      # Data source connection failures
│   ├── EngineNotSupportedException
│   ├── FormatParseException     # Format parsing failures
│   ├── LayerValidationException # Unchecked (RuntimeException)
│   └── TopologyException
└── utils/
    ├── ZipUtil                  # ZIP compress/decompress
    ├── EncodingUtil             # File encoding detection
    ├── SortUtil                 # Natural string sorting
    └── NumUtil                  # Number formatting (remove scientific notation)

常见任务快速参考(Quick Reference: Common Tasks)完整内容见 reference/common-tasks.md

数据格式支持矩阵

| Format | DataFormatType | GeoTools | GDAL | Read | Write | Notes |

|--------|---------------|----------|------|------|-------|-------|

| Shapefile | SHP | Yes | Yes | Yes | Yes | Field names limited to 10 chars |

| GeoJSON | GEOJSON | Yes | Yes | Yes | Yes | |

| FileGDB | FILEGDB | No | Yes | Yes | Yes | Requires GDAL native library |

| PostGIS | POSTGIS | Yes | Yes | Yes | Yes | Connection string as path |

| National Land TXT | TXT | Yes | No | Yes | Yes | Use GtTxtUtil directly |

| WKT | WKT | Yes | No | Yes | No | Geometry-only format |

| ESRI JSON | ESRIJSON | No | No | Yes* | No | *Via GeometryUtil conversion |


数据模型参考

OguLayer(核心)

| Property | Type | Description |

|----------|------|-------------|

| name | String | Layer name |

| alias | String | Layer display name |

| wkid | Integer | EPSG code (e.g. 4490 for CGCS2000) |

| geometryType | GeometryType | POINT, POLYGON, LINESTRING, etc. |

| tolerance | Double | Geometric tolerance |

| fields | List<OguField> | Field definitions |

| features | List<OguFeature> | Feature collection |

| metadata | OguLayerMetadata | Extended metadata |

Methods: fromJSON(String), toJSON(), validate(), filter(OguFeatureFilter), getFeatureCount(), getFieldCount()

OguFeature

| Property | Type | Description |

|----------|------|-------------|

| id | String | Feature identifier |

| geometry | String | Geometry in WKT format |

| attributes | List<OguFieldValue> | Attribute values |

| coordinates | List<OguCoordinate> | Coordinate points (TXT format) |

| rawValues | List<String> | Raw values (TXT format) |

Methods: getAttribute(String fieldName), getValue(String fieldName), setValue(String fieldName, Object value)

OguField

| Property | Type | Description |

|----------|------|-------------|

| name | String | Field name |

| alias | String | Display name |

| description | String | Description |

| dataType | FieldDataType | INTEGER, DOUBLE, STRING, DATE, etc. |

| length | Integer | Max length (for STRING) |

| nullable | Boolean | Nullable flag |

| defaultValue | Object | Default value |

Constructors: OguField(name, alias, dataType), OguField(name, alias, description, dataType)

OguFieldValue

| Property | Type | Description |

|----------|------|-------------|

| field | OguField | Field definition |

| value | Object | Raw value |

Methods: getFieldName(), getStringValue(), getIntValue(), getDoubleValue()

OguCoordinate

| Property | Type | Description |

|----------|------|-------------|

| x | Double | X coordinate (longitude) |

| y | Double | Y coordinate (latitude) |

| z | Double | Z coordinate (elevation, optional) |

| pointNumber | String | Point identifier |

| ringNumber | Integer | Ring/loop number |

Constructors: OguCoordinate(x, y), OguCoordinate(x, y, z)

DbConnBaseModel(PostGIS 连接)

| Property | Type | Description |

|----------|------|-------------|

| dbType | String | Database type |

| host | String | Host address |

| port | String | Port number |

| schema | String | Schema name |

| database | String | Database name |

| user | String | Username |

| passwd | String | Password |


枚举速查

GeometryType

POINT, MULTIPOINT, LINESTRING, LINEARRING, MULTILINESTRING, POLYGON, MULTIPOLYGON, GEOMETRYCOLLECTION

Lookup methods: valueOfByTypeName(String), valueOfByTypeCode(int), valueOfByTypeClass(Class<?>), valueOfByWkbGeometryType(int)

FieldDataType

INTEGER, DOUBLE, STRING, BINARY, DATE, TIME, DATETIME, LONG

Lookup methods: fieldDataTypeByGdalCode(int), fieldDataTypeByTypeClass(Class<?>)

DataFormatType

WKT, GEOJSON, ESRIJSON, SHP, TXT, FILEGDB, POSTGIS, ARCSDE

Properties per value: desc (description), gdalDriverName (GDAL driver name)

GisEngineType

GEOTOOLS, GDAL, AUTO


异常层次

Exception
└── OguException                      # Base checked exception
    ├── DataSourceException           # Data source connection/access failure
    ├── EngineNotSupportedException   # Engine doesn't support the operation/format
    ├── FormatParseException          # Data format parsing failure
    └── TopologyException             # Geometry topology error

RuntimeException
└── LayerValidationException          # Layer data validation failure (unchecked)

架构与设计模式


常见问题

| 问题 | 解决 |

|------|------|

| mvn install 依赖解析失败 | 配置 osgeo 仓库(GeoTools 依赖不在 Maven Central);确认 Maven 3.8+ 与 JDK 17+ |

| 找不到 com.znlgis.ogu4j:ogu4j 依赖 | 该库尚未发布到 Maven Central,先在本仓库执行 mvn install 安装到本地仓库 |

| 运行时报 GDAL 相关 UnsatisfiedLinkError | 本地缺少与 org.gdal:gdal 3.13.0 匹配的原生 GDAL;安装 GDAL 3.13.x,或改用 GisEngineType.GEOTOOLS |

| FileGDB 读写失败 | FileGDB 仅 GDAL 引擎支持:安装原生 GDAL 并使用 GisEngineType.GDAL 或 AUTO |

| Shapefile 字段名被截断 | DBF 规范限制 10 字符,使用 ShpUtil.formatFieldName() 自动截断 |

| PostGIS 连接失败 | 检查连接串格式(PG: host=... port=... dbname=... user=... password=... active_schema=...)与 schema 名称 |


AI 编码约定

  1. Always use OguLayerUtil as the primary entry point for reading/writing GIS data. It handles engine selection and format routing.
  1. Geometry in features is stored as WKT strings. Convert to JTS Geometry objects via GeometryUtil.wkt2Geometry() when you need spatial operations.
  1. Engine selection:
  1. CGCS2000 coordinate system (EPSG:4490) is the default/primary CRS. Projected CRS range: EPSG 4502-4554 (3-degree zones). Use CrsUtil for transformation.
  1. PostGIS connection strings follow the format:

"PG: host=<host> port=<port> dbname=<db> user=<user> password=<pwd> active_schema=<schema>"

  1. Resource management:
  1. Shapefile field names are limited to 10 characters. Use ShpUtil.formatFieldName() to auto-truncate.
  1. OguLayer can be serialized to/from JSON using layer.toJSON() and OguLayer.fromJSON(json) (backed by FastJSON2).
  1. Attribute filtering uses CQL expression syntax (e.g., "population > 1000000 AND name LIKE '%京%'").
  1. Spatial filtering accepts WKT geometry strings (e.g., "POLYGON((115 39, 117 39, 117 41, 115 41, 115 39))").
  1. Two geometry operation styles:
  1. Build with Maven: mvn compile — requires the OSGeo repository for GeoTools dependencies:

```xml

<repository>

<id>osgeo</id>

<url>https://repo.osgeo.org/repository/release/</url>

</repository>

```


典型工作流

以「Shapefile → 面积筛选 → 缓冲 → 投影 → GeoJSON」为例:输入 /data/parcels.shp(EPSG:4326),输出 /data/output.geojson(EPSG:4528)。

import com.znlgis.ogu4j.datasource.OguLayerUtil;
import com.znlgis.ogu4j.engine.enums.*;
import com.znlgis.ogu4j.engine.model.layer.*;
import com.znlgis.ogu4j.engine.util.CrsUtil;
import com.znlgis.ogu4j.geometry.GeometryUtil;
import org.locationtech.jts.geom.Geometry;

// Step 1: Read a Shapefile
OguLayer layer = OguLayerUtil.readLayer(
    DataFormatType.SHP, "/data/parcels.shp",
    null, null, null, GisEngineType.AUTO
);

// Step 2: Filter features by area > 10,000 square units
List<OguFeature> largeParcels = layer.filter(f -> {
    Geometry geom = GeometryUtil.wkt2Geometry(f.getGeometry());
    return GeometryUtil.area(geom) > 10000;
});

// Step 3: Buffer each geometry
for (OguFeature f : largeParcels) {
    Geometry geom = GeometryUtil.wkt2Geometry(f.getGeometry());
    Geometry buffered = GeometryUtil.buffer(geom, 50.0);
    f.setGeometry(GeometryUtil.geometry2Wkt(buffered));
}

// Step 4: Reproject to projected CRS
OguLayer projected = CrsUtil.reproject(layer, 4528);

// Step 5: Export to GeoJSON
OguLayerUtil.writeLayer(
    DataFormatType.GEOJSON, projected,
    "/data/output.geojson", null, null, GisEngineType.AUTO
);

// Step 6: 回读验证——要素数与 CRS 必须与预期一致,否则说明引擎或投影没生效
OguLayer check = OguLayerUtil.readLayer(
    DataFormatType.GEOJSON, "/data/output.geojson",
    null, null, null, GisEngineType.AUTO
);
System.out.println(check.getWkid() + " / " + check.getFeatureCount());

验收:mvn -q -DskipTests package 只说明能编译;实际运行上面的 main,打印的 WKID 应为 4528、要素数等于筛选后数量,output.geojson 用 ogrinfo -so 复查一遍。


AI 使用建议

相关技能

参考资源

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.