使用GeoTools进行GeoJSON和Shp的互相转换

问题背景

最近在做的软件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 有以下要求:

  1. 空间数据和属性数据能正常显示。
  2. 若 GeoJSON 文件配置 crs 属性,需要读取 crs 以设置 shp 的坐标系,否则设置为 WGS84;
  3. 为避免乱码,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(
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值