WebGIS 开发:WKT 转 GeoJSON 的多种实现方案与 Leaflet 集成
在 WebGIS 开发中,数据格式的转换与兼容始终是一个关键挑战。WKT(Well-Known Text)和 GeoJSON 是两种常见的地理空间数据格式。WKT 适合存储与交换,但在 Web 环境下的交互性较弱;GeoJSON 则以其简洁的 JSON 结构,完美契合前端需求。本文将介绍几种将 WKT 转换为 GeoJSON 的实用方法,并结合 Leaflet 地图库演示如何加载渲染。
一、后台转换实现
1. 基于 PostGIS 实现
如果后端数据库支持空间扩展,可以直接利用空间函数处理。以 PostGIS 为例,查询空间属性的 WKT 格式可使用 ST_AsEWKT 函数,而转换为 GeoJSON 则使用 ST_AsGeoJSON。
SELECT ST_AsEWKT(geom), ST_AsGeoJSON(geom) FROM biz_earthquake LIMIT 10;
执行后返回的结果集中,第二列即为 GeoJSON 类型数据。这种方式本质上是直接利用了空间数据库的查询能力,无需额外代码处理,效率较高。
2. GeoTools 实现
若需纯 Java 后端逻辑,可以使用 GeoTools 组件。首先在 pom.xml 中引入依赖:
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-geojson</artifactId>
<version>28.2</version>
</dependency>
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.19.0</version>
</dependency>
核心转换代码如下:
package com.example.geotools.wkt2json;
org.geotools.geojson.geom.GeometryJSON;
org.geotools.geometry.jts.JTSFactoryFinder;
org.locationtech.jts.geom.Geometry;
org.locationtech.jts.geom.GeometryFactory;
org.locationtech.jts.io.WKTReader;
java.io.StringWriter;
{
String {
;
{
JTSFactoryFinder.getGeometryFactory();
(geometryFactory);
reader.read(wkt);
();
();
geometryJson.write(geometry, writer);
json = writer.toString();
} (Exception e) {
e.printStackTrace();
}
json;
}
{
;
wktToJson(wkt);
System.out.println(geoJson);
}
}


