文章目录
- 1. 依赖安装
- 1.1 配置软件源
- 1.2 引入依赖
- 2. 功能实现
- 3. 参考链接
1. 依赖安装
1.1 配置软件源
在项目 pom.xml 添加,
maven 的 settings.xml 配置的源,mirrorOf 不能是 *,不然安装不上
<project>...<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><repository><id>osgeo-snapshot</id><name>OSGeo Snapshot Repository</name><url>https://repo.osgeo.org/repository/snapshot/</url><snapshots><enabled>true</enabled></snapshots><releases><enabled>false</enabled></releases></repository></repositories>
</project>
1.2 引入依赖
geotools 29及以上的版本需要 jdk 11
<project>
...<properties>...<geotools.version>28.5</geotools.version></properties><dependencies>...<dependency><groupId>org.geotools</groupId><artifactId>gt-shapefile</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-geojson</artifactId><version>${geotools.version}</version></dependency></dependencies>
</project>
2. 功能实现
// 新版本 FeatureSource 的包路径有变化,根据IDE提示导入即可
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.geojson.feature.FeatureJSON;import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;public class GeoTools {/**** @param shpFile .shp 文件路径* @return* @throws IOException*/public static String shpToJsonString(String shpFile) throws IOException {ShapefileDataStore dataStore = new ShapefileDataStore(new File(shpFile).toURI().toURL());// 处理中文乱码dataStore.setCharset(Charset.forName("GBK"));FeatureSource featureSource = dataStore.getFeatureSource();FeatureJSON featureJSON = new FeatureJSON();String result = null;try (StringWriter writer = new StringWriter()) {featureJSON.writeFeatureCollection(featureSource.getFeatures(), writer);result = writer.toString();}return result;}
}
3. 参考链接
- Re: [Geotools-gt2-users] Shapefile to GeoJson
- GeoTools读取shp文件中文乱码解决方案汇总