参考文章:
GeoTools:WKT、GeoJson、Feature、FeatureCollection相互转换

转换工具类


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.geotools.data.DataUtilities;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geojson.GeoJSONUtil;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;/*** <p>* 空间处理工具* </p>***/
public class GeoTools {private static final WKTReader READER = new WKTReader();/*** 要素集合根节点*/private static final String[] COLLECTION_TYPE = new String[]{"FeatureCollection"};/*** 地理要素类型*/private static final String[] FEATURES_TYPE = new String[]{"Feature"};/*** 地理数据类型* 点、线、面、几何集合*/private static final String[] GEO_TYPE = new String[]{"Geometry", "Point", "LineString", "Polygon", "MultiPoint", "MultiLineString", "MultiPolygon", "GeometryCollection"};/*** 获取 Geo 几何类型* @param wktStr WKT 字符串* @return Geo 几何类型*/public static String getGeometryType(String wktStr) {String type = null;if (StrUtil.isNotEmpty(wktStr)) {try {Geometry read = READER.read(wktStr);type = read.getGeometryType();}catch (Exception e) {System.out.println("非规范 WKT 字符串:"+ e);e.printStackTrace();}}return type;}/*** 是规范的 WKT* @param wktStr WKT 字符串* @return 是、否*/public static boolean isWkt(String wktStr) {for (String s : GEO_TYPE) {if (wktStr.toLowerCase().startsWith(s.toLowerCase())) {return true;}}return false;}/*** 不是规范的 WKT* @param wktStr WKT 字符串* @return 是、否*/public static boolean isNotWkt(String wktStr) {return !isWkt(wktStr);}/*** 是规范的 GeoJson* @param geoJsonStr GeoJson 字符串* @return 是、否*/public static boolean isGeoJson(String geoJsonStr) {try {JSONObject jsonObject = JSONUtil.parseObj(geoJsonStr);return isGeoJson(jsonObject);}catch (Exception e) {return false;}}/*** 不是规范的 GeoJson* @param geoJsonStr GeoJson 字符串* @return 是、否*/public static boolean isNotGeoJson(String geoJsonStr) {return !isGeoJson(geoJsonStr);}/*** 是规范的 GeoJson* @param geoJson GeoJson 对象* @return 是、否*/public static boolean isGeoJson(JSONObject geoJson) {String type = geoJson.getStr("type");boolean mark = false;// 判断根节点if (ArrayUtil.containsIgnoreCase(COLLECTION_TYPE, type)) {JSONArray jsonArray = geoJson.get("features", JSONArray.class);for (Object jsonStr : jsonArray) {JSONObject jsonObject = JSONUtil.parseObj(jsonStr);type = jsonObject.getStr("type");// 判断地理要素if (ArrayUtil.containsIgnoreCase(FEATURES_TYPE, type)) {type = jsonObject.get("geometry", JSONObject.class).getStr("type");// 判断几何要素mark = ArrayUtil.containsIgnoreCase(GEO_TYPE, type);}if (!mark) {return false;}}}else {// 判断地理要素if (ArrayUtil.containsIgnoreCase(FEATURES_TYPE, type)) {type = geoJson.get("geometry", JSONObject.class).getStr("type");}// 数据是几何数据mark = ArrayUtil.containsIgnoreCase(GEO_TYPE, type);}return mark;}/*** 不是规范的 GeoJson* @param geoJson GeoJson 对象* @return 是、否*/public static boolean isNotGeoJson(JSONObject geoJson) {return !isGeoJson(geoJson);}/*** GeoJson 转 WKT* @param geoJson GeoJson 对象* @return WKT 字符串*/public static String geoJsonToWkt(JSONObject geoJson) {String wkt = null;GeometryJSON gJson = new GeometryJSON();try {if(isGeoJson(geoJson)){String type = geoJson.getStr("type");// 判断是否根节点if (ArrayUtil.containsIgnoreCase(COLLECTION_TYPE, type)) {JSONArray geometriesArray = geoJson.get("features", JSONArray.class);// 定义一个数组装图形对象int size = geometriesArray.size();Geometry[] geometries = new Geometry[size];for (int i = 0; i < size; i++){String str = JSONUtil.parseObj(geometriesArray.get(i)).getStr("geometry");// 使用 GeoUtil 去读取 strReader reader = GeoJSONUtil.toReader(str);Geometry geometry = gJson.read(reader);geometries[i] = geometry;}GeometryCollection geometryCollection = new GeometryCollection(geometries, new GeometryFactory());wkt = geometryCollection.toText();}else {String geoStr = geoJson.toString();// 判断是否地理要素节点if (ArrayUtil.containsIgnoreCase(FEATURES_TYPE, type)) {geoStr = geoJson.getStr("geometry");}Reader reader = GeoJSONUtil.toReader(geoStr);Geometry read = gJson.read(reader);wkt = read.toText();}}} catch (IOException e){System.out.println("GeoJson 转 WKT 出现异常:"+ e);e.printStackTrace();}return wkt;}/*** WKT 转 GeoJson* @param wktStr WKT 字符串* @return GeoJson 对象*/public static JSONObject wktToGeoJson(String wktStr) {JSONObject jsonObject = new JSONObject();try {Geometry geometry = READER.read(wktStr);StringWriter writer = new StringWriter();GeometryJSON geometryJson = new GeometryJSON();geometryJson.write(geometry, writer);jsonObject = JSONUtil.parseObj(writer.toString());} catch (Exception e) {System.out.println("WKT 转 GeoJson 出现异常:"+ e);e.printStackTrace();}return jsonObject;}/*** WKT 转 Feature* @param wktStr WKT 字符串* @return Feature JSON 对象*/public static JSONObject wktToFeature(String wktStr) {JSONObject jsonObject = new JSONObject();try {SimpleFeatureType type = DataUtilities.createType("Link", "geometry:"+getGeometryType(wktStr));SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type);// 按照TYPE中声明的顺序为属性赋值就可以,其他方法我暂未尝试featureBuilder.add(READER.read(wktStr));SimpleFeature feature = featureBuilder.buildFeature(null);StringWriter writer = new StringWriter();FeatureJSON fJson = new FeatureJSON();fJson.writeFeature(feature, writer);jsonObject = JSONUtil.parseObj(writer.toString());}catch (Exception e) {System.out.println("WKT 转 Feature 出现异常:"+ e);e.printStackTrace();}return jsonObject;}/*** WKT 转 FeatureCollection* @param wktStr  WKT 字符串* @return FeatureCollection JSON 对象*/public static JSONObject wktToFeatureCollection(String wktStr) {JSONObject jsonObject = new JSONObject();try {String geometryType = getGeometryType(wktStr);if (StrUtil.isNotEmpty(geometryType)) {SimpleFeatureType type = DataUtilities.createType("Link", "geometry:" + geometryType);SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type);List<SimpleFeature> features = new ArrayList<>();SimpleFeatureCollection collection = new ListFeatureCollection(type, features);featureBuilder.add(READER.read(wktStr));SimpleFeature feature = featureBuilder.buildFeature(null);features.add(feature);StringWriter writer = new StringWriter();FeatureJSON fJson = new FeatureJSON();fJson.writeFeatureCollection(collection, writer);jsonObject = JSONUtil.parseObj(writer.toString());}}catch (Exception e) {System.out.println("WKT 转 FeatureCollection 出现异常:"+ e);e.printStackTrace();}return jsonObject;}
}

测试


import cn.hutool.json.JSONUtil;
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;class GeoToolsTest {String geoJsonStr = "{\n" +"            \"type\":\"Point\",\n" +"            \"coordinates\":[105.380859375,31.57853542647338]\n" +"            }";String geoJsonStr2 = "{\"type\":\"Feature\",\n" +"        \"properties\":{},\n" +"        \"geometry\":{\n" +"            \"type\":\"Point\",\n" +"            \"coordinates\":[105.380859375,31.57853542647338]\n" +"            }\n" +"        }";String geoJsonStr3 = "{\n" +"  \"type\": \"FeatureCollection\",\n" +"  \"features\": [\n" +"        {\"type\":\"Feature\",\n" +"        \"properties\":{},\n" +"        \"geometry\":{\n" +"            \"type\":\"Point\",\n" +"            \"coordinates\":[105.380859375,31.57853542647338]\n" +"            }\n" +"        },\n" +"\t\t{\"type\":\"Feature\",\n" +"        \"properties\":{},\n" +"        \"geometry\":{\n" +"            \"type\":\"Point\",\n" +"            \"coordinates\":[105.380859375,31.57853542647338]\n" +"            }\n" +"        }\n" +"    ]\n" +"}";String[] wktStr = new String[]{"POINT(6 10)", "LINESTRING(3 4,10 50,20 25)", "POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2))","MULTIPOINT(3.5 5.6, 4.8 10.5)", "MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))", "MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3)))","GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))", "POINT ZM (1 1 5 60)", "POINT M (1 1 80)"};@Testvoid getGeometryType() {for (String s : wktStr) {System.out.println("Geo 几何类型:" + GeoTools.getGeometryType(s));}}@Testvoid isWkt() {for (String s : wktStr) {System.out.println("是规范的 WKT:" + GeoTools.isWkt(s));}}@Testvoid isNotWkt() {for (String s : wktStr) {System.out.println("不是规范的 WKT:" + GeoTools.isNotWkt(geoJsonStr2));}}@Testvoid isGeoJson() {System.out.println("是规范的 GeoJson:" + GeoTools.isGeoJson(geoJsonStr3));}@Testvoid isNotGeoJson() {System.out.println("不是规范的 GeoJson:" + GeoTools.isNotGeoJson(geoJsonStr3));}@Testvoid geoJsonToWkt() {System.out.println("GeoJson 转 WKT:" + GeoTools.geoJsonToWkt(JSONUtil.parseObj(geoJsonStr)));System.out.println("GeoJson 转 WKT:" + GeoTools.geoJsonToWkt(JSONUtil.parseObj(geoJsonStr2)));System.out.println("GeoJson 转 WKT:" + GeoTools.geoJsonToWkt(JSONUtil.parseObj(geoJsonStr3)));}@Testvoid wktToGeoJson() {for (String s : wktStr) {System.out.println("WKT 转 GeoJson:" + GeoTools.wktToGeoJson(s));}}@Testvoid wktToFeature() {for (String s : wktStr) {System.out.println("WKT 转 Feature:" + GeoTools.wktToFeature(s));}}@Testvoid wktToFeatureCollection() {for (String s : wktStr) {System.out.println("WKT 转 FeatureCollection:" + GeoTools.wktToFeatureCollection(s));}}
}

GeoTools:WKT、GeoJson、Feature、FeatureCollection相互转换常用工具相关推荐

  1. GeoTools:WKT、GeoJson、Feature、FeatureCollection相互转换

    测试用例: package top.reid.smart.geo;import cn.hutool.json.JSONUtil; import org.junit.jupiter.api.Test;i ...

  2. java 使用GeoTools工具 geojson 与shp 相互转换

    记录使用geotools工具,实现shp和geojson数据互转  爬坑:不使用依赖:vividsolutions ,因为 1.8 与 geotools 20以后版本jts 不一致,会报错. < ...

  3. 解析FeatureCollection(Geotools对geojson操作出现的问题)

    微信搜索:"二十同学" 公众号,欢迎关注一条不一样的成长之路 GeoJSON格式示例 {"type":"FeatureCollection" ...

  4. 【算法竞赛学习】数字中国创新大赛智慧海洋建设-Task1地理数据分析常用工具

    智慧海洋建设-Task1 地理数据分析常用工具 在地理空间数据分析中,常会用到许多地理分析的工具,在本模块中主要是针对常用的shapely.geopandas.folium.kepler.gl.geo ...

  5. 基于GeoTools的GeoJson导入到PostGis实战

    GeoJson是一种对各种地理数据结构进行编码的格式,基于json的地理空间信息数据交换格式.GeoJson对象可以用来表示几何,特征或者特征集合.支持地理点.线.面.多点.多线.多面及几何集合.Ge ...

  6. 智慧海洋建设-Task1地理数据分析常用工具

    地理数据分析常用工具 安装geopandas的库时可以参考我的这篇文章<python库geopandas的安装方法>,https://blog.csdn.net/sjjsaaaa/arti ...

  7. 计算机工具软件应用考试,《计算机常用工具软件》期中考试题

    <计算机常用工具软件>期中考试题 一.单选题 1.使用PartitionMagic创建新分区时,默认的文件系统类型是() A.FAT16 B.FAT32 C.NTFS D.Linux Ex ...

  8. 【算法竞赛学习】气象海洋预测-Task1 气象数据分析常用工具

    气象海洋预测-Task1 气象数据分析常用工具 气象科学中的数据通常包含多个维度,例如本赛题中给出的数据就包含年.月.经度.纬度四个维度,为了便于数据的读取和操作,气象数据通常采用netCDF文件来存 ...

  9. 2020DCIC智慧海洋建设算法赛学习01-赛题北京及地理数据分析常用工具

    序: 本系列的博客旨在学习2020DCIC智能算法赛-智慧海洋建设的优秀方案,对地理数据分析问题积累一些思路和经验. 作为这一系列博客的开篇,这篇博客主要内容包括对赛题的解析和对项目中会用到的一些常用 ...

最新文章

  1. Python之flask结合Bootstrap框架快速搭建Web应用
  2. jquery 向上滚动【四】个人认为好一些,哈
  3. 【深度学习】array, list, tensor,Dataframe,Series之间互相转换总结
  4. IDEA的基本使用:让你的IDEA有飞一般的感觉 | CSDN 博文精选
  5. linux 下安装ecos开发环境,Ubuntu 10.04中安装eCos 3.0
  6. 安卓开发—根据顾客预算显示食物信息
  7. python2与python3区别底层的区别_Python2 与 Python3 的区别(二)?
  8. CSDN积分获得途径
  9. 字节游戏测试开发面试题
  10. OMG,学它!java定时器quartz表达式
  11. VS2015静态库的使用(上)
  12. @开源镜像站(linux系统:Center OS|Ubuntu|Debian)
  13. 计算机基础知识 SERVER
  14. top 和 window.top, iframe 默认高度
  15. 读取采购订单附件(GOS)-[BDS_GOS_CONNECTIONS_GET/SO_DOCUMENT_READ_API1]
  16. 青龙面板2.8版本+Ninja 保姆级 服务器安装jd代挂教程——(一)
  17. Bootstrap3动态添加的元素tooltip不生效
  18. 如何创建数据透视表的方法
  19. 帮百度AI干脏活累活的公司,都死了
  20. OpenCV-Python 立体图像的深度图 | 五十二

热门文章

  1. 电脑设置护眼色的方法
  2. 高德地图开发之地图配置及vue上初始化创建地图
  3. js 文字金额转换成汉字大写金额
  4. 负载均衡、集群和高可用有什么区别?侧重点不同!
  5. R的ggplot2设置多个图组合,加标签,加图例,图的分面
  6. en结尾的单词_形容词加en前后缀变动词的英语单词不一定变动词,其他词性也可以...
  7. 宗海图绘制的关键问题
  8. Unity3D之MeleeWeaponTrail武器轨迹插件的使用
  9. 程序员如何写一份更好的简历!!
  10. 手把手教你在Android-Studio上分析内存泄漏,面试必会