背景
在 WebGIS 开发中,数据格式兼容是常见挑战。WKT(Well-Known Text)常用于数据库存储,而 GeoJSON 更适合前端渲染。本文将分享几种将 WKT 转换为 GeoJSON 的实战方案,并结合 Leaflet 实现地图可视化。
一、后端转换方案
1. 基于 PostGIS 实现
如果数据库支持空间扩展,可直接利用空间函数转换。例如查询地震信息数据:
SELECT ST_AsEWKT(geom) FROM biz_ceic_earthquake LIMIT 10;
若需直接获取 GeoJSON 格式,可使用 ST_AsGeoJSON 函数:
SELECT ST_AsEWKT(geom), ST_AsGeoJSON(geom) FROM biz_ceic_earthquake LIMIT 10;
返回结果的第二列即为 GeoJSON 类型数据。这种方式本质是利用了空间数据库的查询能力,适合后端直接返回给前端。
2. 基于 GeoTools 实现
若需纯后端逻辑转换,可引入 GeoTools 组件。在 Maven 依赖中添加以下配置:
<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.yelang.project.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);
}
}


