当前位置:   article > 正文

【GIS系列】GeoTools简介及工具类分享

geotools

本文将对GeoTools相关概念进行介绍,同时会给大家分享我工作中用到的工具类及使用方法。

作者:后端小肥肠

目录

1.前言

2. GeoTools简介

3. Geotools使用示例

3.1. 开发环境搭建

3.1.1. 所需版本和工具

3.1.2. pom依赖

4. 工具类介绍

4.1. 读取shp工具类

4.1.1 准备数据

4.1.2. 部分方法

4.1.3. 完整工具类代码

4.2. 坐标转换工具类

4.2.1. 准备数据

4.2.2. 完整工具类代码

5. 结语

6. 参考链接 


1.前言

GeoTools是一个功能强大的开源GIS工具库,为地理空间数据处理和分析提供了丰富的功能和便利的接口。无论您是GIS专业人士还是对地理空间数据感兴趣的开发人员,掌握GeoTools都是必不可少的。本文将从基本概念入手,介绍GeoTools的功能和使用方法,并重点分享一些实用的工具类和技巧,希望能为您在GIS应用开发中提供帮助和启发。

2. GeoTools简介

GeoTools是一个开源的Java库,用于处理和分析地理空间数据。它提供了一系列用于读取、写入、处理和可视化地理空间数据的工具和API。以下是与GeoTools相关的一些重要概念:

  1. 地理空间数据(Geospatial Data): GeoTools主要用于处理地理空间数据,这包括地图、地形、卫星影像、矢量数据等地理信息。这些数据通常具有地理坐标信息和地理属性信息。

  2. 地理坐标系统(Geographic Coordinate System,GCS): 地理坐标系统是用于在地球上定位点的一种方法。GeoTools支持多种地理坐标系统,包括经纬度坐标系统等。

  3. 投影坐标系统(Projected Coordinate System,PCS): 投影坐标系统是将地球表面的地理坐标投影到平面上的一种方法。GeoTools提供了许多常用的投影方法和投影坐标系统的支持。

  4. 数据格式(Data Formats): GeoTools支持多种地理空间数据格式,如Shapefile、GeoJSON、KML、GML等,可以方便地读取和写入这些数据格式。

  5. 空间分析(Spatial Analysis): GeoTools提供了丰富的空间分析功能,包括缓冲区分析、空间查询、空间叠加分析等,可以帮助用户进行地理空间数据的处理和分析。

总的来说,GeoTools是一个功能丰富的GIS工具库,提供了丰富的功能和工具,可以帮助用户处理和分析各种地理空间数据,并构建地理空间应用。

3. Geotools使用示例

3.1. 开发环境搭建

3.1.1. 所需版本和工具
依赖版本
Spring Boot2.6.14
GeoTools27-SNAPSHOT
java1.8以上
ArcGis10.8

我这里用的不是GeoTools的最新版本,需要最新版本的同学可登录GeoTools的官网(GeoTools The Open Source Java GIS Toolkit — GeoTools)查看最新版本和其使用规则。

如上图所示,最新版本的GeoTools跟java11适配。

3.1.2. pom依赖
  1. <dependency>
  2. <groupId>org.geotools</groupId>
  3. <artifactId>gt-shapefile</artifactId>
  4. <version>${geotools.version}</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.geotools</groupId>
  8. <artifactId>gt-geojson</artifactId>
  9. <version>${geotools.version}</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.geotools</groupId>
  13. <artifactId>gt-swing</artifactId>
  14. <version>${geotools.version}</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-validation</artifactId>
  28. </dependency>

4. 工具类介绍

4.1. 读取shp工具类

4.1.1 准备数据

打开ArcGis绘制面数据,我这里绘制了4490坐标系的几个面要素。

4.1.2. 部分方法

1. 读取shp中的空间要素信息(wkt)

  1. public static List<String> getWktFromShp(String shpPath) {
  2. List<String> shpList = new ArrayList<>();
  3. SimpleFeatureCollection simpleFeatureCollection = null;
  4. try {
  5. //获取文件
  6. File file = new File(shpPath);
  7. // 读取到数据存储中
  8. FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
  9. // 获取特征资源
  10. SimpleFeatureSource simpleFeatureSource = dataStore.getFeatureSource();
  11. // 要素集合
  12. simpleFeatureCollection = simpleFeatureSource.getFeatures();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. // 获取要素迭代器
  17. SimpleFeatureIterator featureIterator = simpleFeatureCollection.features();
  18. while (featureIterator.hasNext()) {
  19. // 要素对象
  20. SimpleFeature feature = featureIterator.next();
  21. Object geometryText = feature.getDefaultGeometry();
  22. log.info(geometryText.toString());
  23. shpList.add(geometryText.toString());
  24. }
  25. featureIterator.close();
  26. return shpList;
  27. }

2. 运行结果

3. 读取shp文件并将其转换为Geojson

  1. /**
  2. * 构造Geojson结构体
  3. * @param featuresJson
  4. * @return
  5. */
  6. public static JSONObject buildGeoJson(JSONArray featuresJson) {
  7. JSONObject Geojson = new JSONObject();
  8. Geojson.put("type", "FeatureCollection");
  9. Geojson.put("features", featuresJson);
  10. return Geojson;
  11. }
  12. /**
  13. * 构造Geojson的features部分 单个
  14. *
  15. * @param geoObject
  16. * @param properties
  17. * @return
  18. */
  19. public static JSONObject buildFeature(Map geoObject, Map properties) {
  20. JSONObject featureObject = new JSONObject();
  21. Map featureMap = new HashMap();
  22. featureMap.put("type", "Feature");
  23. featureMap.putAll(geoObject);
  24. featureMap.put("properties", properties);
  25. featureObject.putAll(featureMap);
  26. return featureObject;
  27. }
  28. /**
  29. * 获取空间信息并构造为Map
  30. * @param wkt
  31. * @return
  32. */
  33. public static Map getGeoMap(String wkt) {
  34. Map<String, Object> geoMap = new HashMap<>();
  35. String json = null;
  36. try {
  37. WKTReader reader = new WKTReader();
  38. Geometry geometry = reader.read(wkt);
  39. StringWriter writer = new StringWriter();
  40. GeometryJSON g = new GeometryJSON();
  41. g.write(geometry, writer);
  42. geoMap.put("geometry", writer);
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. return geoMap;
  47. }
  48. /**
  49. * 基于shp构造geojson并返回
  50. *
  51. * @param shpPath
  52. * @return
  53. */
  54. public static JSONObject buildGeojsonFromShp(String shpPath) {
  55. JSONArray featureArray = new JSONArray();
  56. // List<String>shpList=new ArrayList<>();
  57. SimpleFeatureCollection simpleFeatureCollection = null;
  58. try {
  59. // 要素合集
  60. //获取文件
  61. File file = new File(shpPath);
  62. // 读取到数据存储中
  63. ShapefileDataStore dataStore = (ShapefileDataStore) FileDataStoreFinder.getDataStore(file);
  64. dataStore.setCharset(Charset.forName("GBK"));
  65. // 获取特征资源
  66. SimpleFeatureSource simpleFeatureSource = dataStore.getFeatureSource();
  67. // 要素集合
  68. simpleFeatureCollection = simpleFeatureSource.getFeatures();
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. SimpleFeatureIterator featureIterator = simpleFeatureCollection.features();
  73. // // 要素数量
  74. int featureSize = simpleFeatureCollection.size();
  75. // log.info("要素数量"+featureSize);
  76. //创建properties Map
  77. while (featureIterator.hasNext()) {
  78. // 要素对象
  79. SimpleFeature feature = featureIterator.next();
  80. Collection<Property> propertyCollection = (Collection<Property>) feature.getValue();
  81. //填充属性map
  82. Map<String, Object> properMap = new HashMap<>();
  83. for (Property property : propertyCollection) {
  84. if (property.getName().toString().equals("the_geom")) {
  85. continue;
  86. }
  87. properMap.put(property.getName().toString(), property.getValue());
  88. }
  89. //获取geo信息
  90. Object geometryText = feature.getDefaultGeometry();
  91. Map geoMap = getGeoMap(geometryText.toString());
  92. JSONObject featureObject = buildFeature(geoMap, properMap);
  93. featureArray.add(featureObject);
  94. }
  95. featureIterator.close();
  96. JSONObject GeoJson = buildGeoJson(featureArray);
  97. return GeoJson;
  98. }

4. 运行结果

4.1.3. 完整工具类代码
  1. import lombok.extern.slf4j.Slf4j;
  2. import org.geotools.data.FileDataStore;
  3. import org.geotools.data.FileDataStoreFinder;
  4. import org.geotools.data.shapefile.ShapefileDataStore;
  5. import org.geotools.data.simple.SimpleFeatureCollection;
  6. import org.geotools.data.simple.SimpleFeatureIterator;
  7. import org.geotools.data.simple.SimpleFeatureSource;
  8. import org.geotools.geojson.geom.GeometryJSON;
  9. import org.json.simple.JSONArray;
  10. import org.json.simple.JSONObject;
  11. import org.locationtech.jts.geom.Geometry;
  12. import org.locationtech.jts.geom.GeometryFactory;
  13. import org.locationtech.jts.geom.Point;
  14. import org.locationtech.jts.io.ParseException;
  15. import org.locationtech.jts.io.WKTReader;
  16. import org.locationtech.jts.io.WKTWriter;
  17. import org.opengis.feature.Property;
  18. import org.opengis.feature.simple.SimpleFeature;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.io.StringWriter;
  22. import java.nio.charset.Charset;
  23. import java.util.*;
  24. /**
  25. * @version 1.0
  26. * @description: gis工具类
  27. * @author: chenss
  28. * @date 2024-03-14 16:19
  29. */
  30. @Slf4j
  31. public class GisUtil {
  32. public static void main(String[] args) {
  33. JSONObject Geojson=buildGeojsonFromShp("D:\\arcgisdata\\mesh4490.shp");
  34. log.info(Geojson.toJSONString());
  35. // List<String> wkts = getWktFromShp("D:\\arcgisdata\\mesh4490.shp");
  36. // for (String wkt : wkts) {
  37. // log.info(wkt);
  38. // }
  39. }
  40. /**
  41. * 构造Geojson结构体
  42. * @param featuresJson
  43. * @return
  44. */
  45. public static JSONObject buildGeoJson(JSONArray featuresJson) {
  46. JSONObject Geojson = new JSONObject();
  47. Geojson.put("type", "FeatureCollection");
  48. Geojson.put("features", featuresJson);
  49. return Geojson;
  50. }
  51. /**
  52. * 构造Geojson的features部分 单个
  53. *
  54. * @param geoObject
  55. * @param properties
  56. * @return
  57. */
  58. public static JSONObject buildFeature(Map geoObject, Map properties) {
  59. JSONObject featureObject = new JSONObject();
  60. Map featureMap = new HashMap();
  61. featureMap.put("type", "Feature");
  62. featureMap.putAll(geoObject);
  63. featureMap.put("properties", properties);
  64. featureObject.putAll(featureMap);
  65. return featureObject;
  66. }
  67. /**
  68. * 获取空间信息并构造为Map
  69. * @param wkt
  70. * @return
  71. */
  72. public static Map getGeoMap(String wkt) {
  73. Map<String, Object> geoMap = new HashMap<>();
  74. String json = null;
  75. try {
  76. WKTReader reader = new WKTReader();
  77. Geometry geometry = reader.read(wkt);
  78. StringWriter writer = new StringWriter();
  79. GeometryJSON g = new GeometryJSON();
  80. g.write(geometry, writer);
  81. geoMap.put("geometry", writer);
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. }
  85. return geoMap;
  86. }
  87. /**
  88. * 只读取geo信息 wkt
  89. *
  90. * @param shpPath
  91. * @return
  92. */
  93. public static List<String> getWktFromShp(String shpPath) {
  94. List<String> shpList = new ArrayList<>();
  95. SimpleFeatureCollection simpleFeatureCollection = null;
  96. try {
  97. //获取文件
  98. File file = new File(shpPath);
  99. // 读取到数据存储中
  100. FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
  101. // 获取特征资源
  102. SimpleFeatureSource simpleFeatureSource = dataStore.getFeatureSource();
  103. // 要素集合
  104. simpleFeatureCollection = simpleFeatureSource.getFeatures();
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. }
  108. // 获取要素迭代器
  109. SimpleFeatureIterator featureIterator = simpleFeatureCollection.features();
  110. while (featureIterator.hasNext()) {
  111. // 要素对象
  112. SimpleFeature feature = featureIterator.next();
  113. Object geometryText = feature.getDefaultGeometry();
  114. log.info(geometryText.toString());
  115. shpList.add(geometryText.toString());
  116. }
  117. featureIterator.close();
  118. return shpList;
  119. }
  120. /**
  121. * 基于shp构造geojson并返回
  122. *
  123. * @param shpPath
  124. * @return
  125. */
  126. public static JSONObject buildGeojsonFromShp(String shpPath) {
  127. JSONArray featureArray = new JSONArray();
  128. // List<String>shpList=new ArrayList<>();
  129. SimpleFeatureCollection simpleFeatureCollection = null;
  130. try {
  131. // 要素合集
  132. //获取文件
  133. File file = new File(shpPath);
  134. // 读取到数据存储中
  135. ShapefileDataStore dataStore = (ShapefileDataStore) FileDataStoreFinder.getDataStore(file);
  136. dataStore.setCharset(Charset.forName("GBK"));
  137. // 获取特征资源
  138. SimpleFeatureSource simpleFeatureSource = dataStore.getFeatureSource();
  139. // 要素集合
  140. simpleFeatureCollection = simpleFeatureSource.getFeatures();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. SimpleFeatureIterator featureIterator = simpleFeatureCollection.features();
  145. // // 要素数量
  146. int featureSize = simpleFeatureCollection.size();
  147. // log.info("要素数量"+featureSize);
  148. //创建properties Map
  149. while (featureIterator.hasNext()) {
  150. // 要素对象
  151. SimpleFeature feature = featureIterator.next();
  152. Collection<Property> propertyCollection = (Collection<Property>) feature.getValue();
  153. //填充属性map
  154. Map<String, Object> properMap = new HashMap<>();
  155. for (Property property : propertyCollection) {
  156. if (property.getName().toString().equals("the_geom")) {
  157. continue;
  158. }
  159. properMap.put(property.getName().toString(), property.getValue());
  160. }
  161. //获取geo信息
  162. Object geometryText = feature.getDefaultGeometry();
  163. Map geoMap = getGeoMap(geometryText.toString());
  164. JSONObject featureObject = buildFeature(geoMap, properMap);
  165. featureArray.add(featureObject);
  166. }
  167. featureIterator.close();
  168. JSONObject GeoJson = buildGeoJson(featureArray);
  169. return GeoJson;
  170. }
  171. /**
  172. * 根据给定的wkt面求出中心点,并以wkt形式返回
  173. */
  174. public static String calculateCenter(String wktPolygon) throws ParseException {
  175. // 创建 WKT 解析器和写入器
  176. WKTReader reader = new WKTReader(new GeometryFactory());
  177. WKTWriter writer = new WKTWriter();
  178. // 解析面的几何对象
  179. Geometry geometry = reader.read(wktPolygon);
  180. // 计算面的中心点
  181. Point center = geometry.getCentroid();
  182. // 将中心点转换为 WKT 格式
  183. String wktCenter = writer.write(center);
  184. return wktCenter;
  185. }
  186. }

4.2. 坐标转换工具类

我这个坐标转换工具只应用于同椭球(本文示例为2000坐标系-EPSG:4490)坐标投影转换。已云南的投影带为33-35,对应的EPSG为4521、4522、4523。

4.2.1. 准备数据

1. 准备4490、4521、4522、4523的shp

2. 获取.prj中坐标描述信息

3. 将坐标描述信息存放到常量Map中

  1. static final Map<String,String> projMap=new HashMap();
  2. static {
  3. projMap.put("4522","PROJCS["CGCS2000_3_Degree_GK_Zone_34",GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",34500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",102.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]");
  4. projMap.put("4490","GEOGCS["China Geodetic Coordinate System 2000",\n" +
  5. " DATUM["China_2000",\n" +
  6. " SPHEROID["CGCS2000",6378137,298.257222101,\n" +
  7. " AUTHORITY["EPSG","1024"]],\n" +
  8. " AUTHORITY["EPSG","1043"]],\n" +
  9. " PRIMEM["Greenwich",0,\n" +
  10. " AUTHORITY["EPSG","8901"]],\n" +
  11. " UNIT["degree",0.0174532925199433,\n" +
  12. " AUTHORITY["EPSG","9122"]],\n" +
  13. " AUTHORITY["EPSG","4490"]]");
  14. projMap.put("4521","PROJCS["CGCS2000_3_Degree_GK_Zone_33",GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",33500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",99.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]");
  15. projMap.put("4523","PROJCS["CGCS2000_3_Degree_GK_Zone_35",GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",35500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",105.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]");
  16. }
4.2.2. 完整工具类代码
  1. import lombok.extern.slf4j.Slf4j;
  2. import org.geotools.data.FeatureWriter;
  3. import org.geotools.data.FileDataStoreFactorySpi;
  4. import org.geotools.data.Transaction;
  5. import org.geotools.data.shapefile.ShapefileDataStore;
  6. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  7. import org.geotools.data.simple.SimpleFeatureIterator;
  8. import org.geotools.data.simple.SimpleFeatureSource;
  9. import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
  10. import org.geotools.geometry.jts.JTS;
  11. import org.geotools.referencing.CRS;
  12. import org.locationtech.jts.geom.Geometry;
  13. import org.opengis.feature.simple.SimpleFeature;
  14. import org.opengis.feature.simple.SimpleFeatureType;
  15. import org.opengis.referencing.crs.CoordinateReferenceSystem;
  16. import org.opengis.referencing.operation.MathTransform;
  17. import java.io.File;
  18. import java.io.Serializable;
  19. import java.util.HashMap;
  20. import java.util.Locale;
  21. import java.util.Map;
  22. @Slf4j
  23. public class ProjTransUtil {
  24. static final Map<String,String> projMap=new HashMap();
  25. static {
  26. projMap.put("4522","PROJCS[\"CGCS2000_3_Degree_GK_Zone_34\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",34500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",102.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]");
  27. projMap.put("4490","GEOGCS[\"China Geodetic Coordinate System 2000\",\n" +
  28. " DATUM[\"China_2000\",\n" +
  29. " SPHEROID[\"CGCS2000\",6378137,298.257222101,\n" +
  30. " AUTHORITY[\"EPSG\",\"1024\"]],\n" +
  31. " AUTHORITY[\"EPSG\",\"1043\"]],\n" +
  32. " PRIMEM[\"Greenwich\",0,\n" +
  33. " AUTHORITY[\"EPSG\",\"8901\"]],\n" +
  34. " UNIT[\"degree\",0.0174532925199433,\n" +
  35. " AUTHORITY[\"EPSG\",\"9122\"]],\n" +
  36. " AUTHORITY[\"EPSG\",\"4490\"]]");
  37. projMap.put("4521","PROJCS[\"CGCS2000_3_Degree_GK_Zone_33\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",33500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",99.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]");
  38. projMap.put("4523","PROJCS[\"CGCS2000_3_Degree_GK_Zone_35\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",35500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]");
  39. }
  40. /**
  41. * 根据传入wkt获取数据坐标系
  42. * @param wkt
  43. * @return
  44. */
  45. public static String getProj(String wkt){
  46. String resEpsg="";
  47. int lonLatStart=-1;
  48. //根据wkt字符串判断平面坐标位于哪一度带
  49. try {
  50. for (int i = 0; i < wkt.length(); i++) {
  51. if(Integer.valueOf(wkt.charAt(i))>=48&&Integer.valueOf(wkt.charAt(i))<58){
  52. lonLatStart=i;
  53. break;
  54. }
  55. }
  56. int lonLatEnd=wkt.indexOf(",");
  57. String projLonLat=wkt.substring(lonLatStart,lonLatEnd);
  58. String[]lonlat=projLonLat.split(" ");
  59. String projLon=lonlat[0];
  60. if(projLon.substring(0,2).equals("33")){
  61. resEpsg="4521";
  62. }else if(projLon.substring(0,2).equals("34")){
  63. resEpsg="4522";
  64. }else if(projLon.substring(0,2).equals("35")){
  65. resEpsg="4523";
  66. }
  67. else
  68. return "4490";
  69. } catch (Exception e) {
  70. log.info(wkt+"出错");
  71. log.error(e.getMessage(),e);
  72. }
  73. return resEpsg;
  74. }
  75. /**
  76. * 坐标转换
  77. * @param geom
  78. * @param sourceEpsg
  79. * @return
  80. */
  81. public static Geometry lonlat2WebMactor(Geometry geom,String sourceEpsg){
  82. try{
  83. //这里是以OGC WKT形式定义的是World Mercator投影,网页地图一般使用该投影
  84. CoordinateReferenceSystem crsSource=CRS.parseWKT(projMap.get(sourceEpsg));
  85. CoordinateReferenceSystem crsTarget = CRS.parseWKT(projMap.get("4490"));
  86. // 投影转换
  87. // MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crsTarget);
  88. MathTransform transform = CRS.findMathTransform(crsSource, crsTarget);
  89. return JTS.transform(geom, transform);
  90. }
  91. catch (Exception e) {
  92. // TODO Auto-generated catch block
  93. log.error(e.getMessage(),e);
  94. return null;
  95. }
  96. }
  97. /**
  98. *给定inputshp转换为targetEpsg坐标系,并输出到outputShp位置
  99. * @param inputShp
  100. * @param outputShp
  101. * @param targetEpsg
  102. * @return
  103. */
  104. public static Map projectShape(String inputShp, String outputShp,String targetEpsg){
  105. Map map = new HashMap();
  106. try {
  107. //源shape文件
  108. ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(inputShp).toURI().toURL());
  109. //创建目标shape文件对象
  110. Map<String, Serializable> params = new HashMap<String, Serializable>();
  111. FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
  112. File file=FileUtil.createFileByPath(outputShp);
  113. // if(!file.exists()){
  114. params.put(ShapefileDataStoreFactory.URLP.key,file.toURI().toURL());
  115. ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);
  116. // Charset charset = Charset.forName("UTF-8");
  117. // ds.setCharset(charset);
  118. // 设置属性
  119. SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);
  120. //下面这行还有其他写法,根据源shape文件的simpleFeatureType可以不用retype,而直接用fs.getSchema设置
  121. // CoordinateReferenceSystem crs = CRS.parseWKT(strWKTMercator);
  122. CoordinateReferenceSystem crs = CRS.parseWKT(projMap.get("4490"));
  123. ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), crs));
  124. //设置writer
  125. FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
  126. //写记录
  127. SimpleFeatureIterator it = fs.getFeatures().features();
  128. try {
  129. while (it.hasNext()) {
  130. SimpleFeature f = it.next();
  131. SimpleFeature fNew = writer.next();
  132. fNew.setAttributes(f.getAttributes());
  133. Geometry geom = lonlat2WebMactor((Geometry)f.getAttribute("the_geom"),targetEpsg);
  134. fNew.setAttribute("the_geom", geom);
  135. }
  136. }
  137. finally {
  138. it.close();
  139. }
  140. writer.write();
  141. writer.close();
  142. ds.dispose();
  143. shapeDS.dispose();
  144. // }
  145. map.put("status", "success");
  146. map.put("message", outputShp);
  147. }
  148. catch (Exception e) {
  149. log.error(e.getMessage(),e);
  150. map.put("status", "failure");
  151. map.put("message", e.getMessage());
  152. }
  153. return map;
  154. }
  155. // public static void main(String[] args) {
  156. // String input="D:\\jsonshp\\test.shp";
  157. // String output="D:\\jsonshp\\test4490.shp";
  158. // projectShape(input,output);
  159. // }
  160. }

5. 结语

本文对GeoTools的基本概念进行了简介,之后介绍了Geotools的工具类及其具体用法。下一篇文章将讲解Postgis+Geotools+MybatisPlus实现数据的读取,写入及前端展示。对Gis开发领域感兴趣的同学可动动你们发财的小手点点关注~

6. 参考链接 

常见2000坐标系对应的EPSG代号 - 知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/476152
推荐阅读
相关标签
  

闽ICP备14008679号