问题背景
最近在做的软件POIKit需要提供 geojson 与 shp 数据的相互转换,考虑使用 GeoTools 实现该功能,GeoTools 是基于 OGC 规范的开源 Java GIS 库,支持如 csv、geojson、shapefile、wfs 等矢量数据格式的读取和转换,但官网仅提供了关于csv 转换至 shp的教程,国内外关于二者数据转换的文章也不太丰富,经过了一番挫折之后,我找到了一种实现二者互相转换的简单方式。
使用 Maven 安装 geotools
本次使用 Maven 构建,pom.xml 中关于 geotools 的引用如下:
<repositories>
<repository>
<id>osgeo</id>
<name>OSGeo Release Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<properties>
<geotools.version>25.0</geotools.version>
</properties>
<dependency>
<!-- shapefile组件 -->
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<!-- geojson组件 -->
<groupId>org.geotools</groupId>
<artifactId>gt-geojson</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<!-- geojson数据存储 -->
<groupId>org.geotools</groupId>
<artifactId>gt-geojsondatastore</artifactId>
<version>${geotools.version}</version>
</dependency>
注意:国内用户一般会配置阿里云镜像,而一些镜像配置的教程往往是错误的,往往会将mirrorOf
参数设置为*,这种情况下,阿里云镜像会拦截所有的 maven 请求,并向自己的镜像仓库请求数据下载,但事实上,阿里云镜像只提供对中央资源的镜像,不包含 GeoTools 的资源,因此这种情况下,maven 无法获取我们需要的 jar 包。因此,我们需要将mirrorOf
参数值设置为central,同时配置 repository。
<!-- 阿里云镜像 -->
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
以上是配置 repository 的简要原因,详细介绍可以参见Maven 中 GeoTools 的引入 - Maven 的 repository 与 mirror。
GeoJSON To Shp
如果懒得看分析,可以直接跳转至GeoJSON To Shp查看完整代码。
正确的将 GeoJSON 转为 Shp 有以下要求:
- 空间数据和属性数据能正常显示。
- 若 GeoJSON 文件配置 crs 属性,需要读取 crs 以设置 shp 的坐标系,否则设置为 WGS84;
- 为避免乱码,shp 数据应提供 cpg 格式文件;
假设 geojson 文件路径为geojsonPath,输出 shp 文件路径为shpPath。
首先根据文件路径获得 FeatureCollection:
InputStream in = new FileInputStream(geojsonPath);
GeometryJSON gjson = new GeometryJSON();
FeatureJSON fjson = new FeatureJSON(gjson);
FeatureCollection<SimpleFeatureType, SimpleFeature> features = fjson.readFeatureCollection(in);
插一句:如果是 geojson 字符串呢?只需要:
Reader reader = new StringReader(