范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文

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

  记录使用geotools工具,实现shp和geojson数据互转
  爬坑:不使用依赖:vividsolutions ,因为 1.8 与 geotools 20以后版本jts 不一致,会报错。com.vividsolutions
  jts
  1.8
  pom
  
  1. 引起pom依赖jar org.geotools
  gt-shapefile
  20.3
  
  org.geotools
  gt-api
  20.3
  
  org.geotools
  gt-geojson
  20.3
  
  org.geotools
  gt-geometry
  20.3
  
  org.geotools
  gt-jts-wrapper
  20.3
  
  org.geotools
  gt-main
  20.3
  
  org.geotools
  gt-epsg-hsql
  20.3
  
  org.geotools
  gt-opengis
  20.3
  
  org.geotools
  gt-data
  20.3
  
  org.geotools
  gt-referencing
  20.3
  
  com.alibaba
  fastjson
  1.2.83
  
  
  org.apache.maven.plugins
  maven-compiler-plugin
  3.0
  1.8
  1.8
  true
  
  
  
  
  2. 上代码,自动识别坐标系,默认为84坐标 import com.alibaba.fastjson.JSON;
  import com.alibaba.fastjson.JSONArray;
  import com.alibaba.fastjson.JSONObject;
  import org.geotools.referencing.CRS;
  import org.locationtech.jts.geom.*;
  import org.geotools.data.FeatureWriter;
  import org.geotools.data.Transaction;
  import org.geotools.data.shapefile.ShapefileDataStore;
  import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  import org.geotools.data.simple.SimpleFeatureCollection;
  import org.geotools.data.simple.SimpleFeatureIterator;
  import org.geotools.data.simple.SimpleFeatureSource;
  import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
  import org.geotools.geojson.feature.FeatureJSON;
  import org.geotools.geojson.geom.GeometryJSON;
  import org.geotools.referencing.crs.DefaultGeographicCRS;
  import org.opengis.feature.simple.SimpleFeature;
  import org.opengis.feature.simple.SimpleFeatureType;
  import org.opengis.referencing.crs.CoordinateReferenceSystem;
  import java.io.*;
  import java.nio.charset.Charset;
  import java.util.*;
  /**
  * @author qiaobing1226
  * @since 2022/10/28 上午10:52
  * 参考:https://blog.csdn.net/qiaobing1226/article/details/127612665
  */
  public class Shp2GeojsonUtils {
  private static final String POINT = "Point";
  private static final String MULTIPOINT = "MultiPoint";
  private static final String LINESTRING = "LineString";
  private static final String MULTILINESTRING = "MultiLineString";
  private static final String POLYGON = "Polygon";
  private static final String MULTIPOLYGON = "MultiPolygon";
  private static final String THE_GEOM = "the_geom";
  private static final String PROPERTIES = "properties";
  private static final String GEOMETRY = "geometry";
  private static final String GBK = "GBK";
  /**
  * geoJson转换为shp文件
  *
  * @param jsonPath
  * @param shpPath
  * @return
  */
  public static Map geoJson2Shape(String jsonPath, String shpPath) {
  Map map = new HashMap<>();
  GeometryJSON geoJson = new GeometryJSON();
  try {
  JSONObject json = readGeoJsonFile(jsonPath);
  JSONArray features = (JSONArray) json.get("features");
  JSONObject feature0 = JSONObject.parseObject(features.get(0).toString());
  // 获取属性名称
  Set properties = JSONObject.parseObject(feature0.getString(PROPERTIES)).keySet();
  String strType = ((JSONObject) feature0.get(GEOMETRY)).getString("type");
  String strCrs = json.getJSONObject("crs").getJSONObject(PROPERTIES).getString("name");
  CoordinateReferenceSystem crs = CRS.decode(strCrs);
  ShapefileDataStore shapefileDataStore = dataStore(properties, strType, shpPath, crs);
  if (shapefileDataStore == null) {
  return map;
  }
  // 设置Writer
  FeatureWriter writer = shapefileDataStore.getFeatureWriter(shapefileDataStore.getTypeNames()[0],
  Transaction.AUTO_COMMIT);
  for (int i = 0, len = features.size(); i < len; i++) {
  String strFeature = features.get(i).toString();
  Reader reader = new StringReader(strFeature);
  SimpleFeature feature = writer.next();
  switch (strType) {
  case POINT:
  feature.setAttribute(THE_GEOM, geoJson.readPoint(reader));
  break;
  case MULTIPOINT:
  feature.setAttribute(THE_GEOM, geoJson.readMultiPoint(reader));
  break;
  case LINESTRING:
  feature.setAttribute(THE_GEOM, geoJson.readLine(reader));
  break;
  case MULTILINESTRING:
  feature.setAttribute(THE_GEOM, geoJson.readMultiLine(reader));
  break;
  case POLYGON:
  feature.setAttribute(THE_GEOM, geoJson.readPolygon(reader));
  break;
  case MULTIPOLYGON:
  feature.setAttribute(THE_GEOM, geoJson.readMultiPolygon(reader));
  break;
  }
  Iterator iterator = properties.iterator();
  while (iterator.hasNext()) {
  String str = iterator.next().toString();
  JSONObject element = JSONObject.parseObject(features.get(i).toString());
  feature.setAttribute(str, JSONObject.parseObject(element.getString(PROPERTIES)).get(str));
  }
  writer.write();
  }
  writer.close();
  shapefileDataStore.dispose();
  map.put("status", 200);
  map.put("message", "shp转换success");
  } catch (Exception e) {
  map.put("status", 400);
  map.put("message", e.getMessage());
  e.printStackTrace();
  }
  return map;
  }
  /**
  * 读取geojosn文件
  *
  * @param jsonPath
  * @return
  */
  private static JSONObject readGeoJsonFile(String jsonPath) {
  // 读文件到Stringbuffer
  StringBuffer sb = new StringBuffer();
  BufferedReader br = null;
  try {
  br = new BufferedReader(new FileReader(jsonPath));
  String str;
  while ((str = br.readLine()) != null) {// 逐行读取
  sb.append(str + "r ");
  }
  br.close();
  } catch (Exception e) {
  if (br != null) {
  try {
  br.close();
  } catch (Exception exception) {
  exception.printStackTrace();
  }
  }
  e.printStackTrace();
  }
  return JSONObject.parseObject(sb.toString());
  }
  /**
  * 设置shp文件属性
  *
  * @param properties
  * @param strType
  * @param shpPath
  * @return
  */
  private static ShapefileDataStore dataStore(Set properties, String strType, String shpPath, CoordinateReferenceSystem crs) {
  try {
  Class<?> geoType = null;
  switch (strType) {
  case POINT:
  geoType = Point.class;
  break;
  case MULTIPOINT:
  geoType = MultiPoint.class;
  break;
  case LINESTRING:
  geoType = LineString.class;
  break;
  case MULTILINESTRING:
  geoType = MultiLineString.class;
  break;
  case POLYGON:
  geoType = Polygon.class;
  break;
  case MULTIPOLYGON:
  geoType = MultiPolygon.class;
  break;
  }
  // 创建shape文件对象
  File file = new File(shpPath);
  Map params = new HashMap();
  params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
  ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
  // 定义图形信息和属性信息
  SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
  //默认84坐标
  tb.setCRS(crs == null ? DefaultGeographicCRS.WGS84 : crs);
  tb.setName("shapefile");
  // 类型,Point/MultiPoint/LineString/MultiLineString/Polygon/MultiPolygon
  tb.add("the_geom", geoType);
  Iterator propertiesIter = properties.iterator();
  // 设置属性
  while (propertiesIter.hasNext()) {
  String str = propertiesIter.next().toString();
  // 此处设置为string
  tb.add(str, String.class);
  }
  ds.createSchema(tb.buildFeatureType());
  // 设置编码
  Charset charset = Charset.forName(GBK);
  ds.setCharset(charset);
  return ds;
  } catch (Exception ex) {
  ex.printStackTrace();
  }
  return null;
  }
  /**
  * shp文件转换geojson数据
  *
  * @param shpPath
  * @return
  */
  public static Map shp2Geojson(String shpPath, String jsonPath) {
  Map map = new HashMap();
  //新建json对象
  JSONObject geojsonObject = new JSONObject();
  geojsonObject.put("type", "FeatureCollection");
  try {
  JSONArray array = new JSONArray();
  String fileName = readShpContent(shpPath, array);
  geojsonObject.put("features", array);
  geojsonObject.put("name", fileName);
  String crs = getCoordinateSystemWKT(shpPath);
  //GEOGCS表示这个是地址坐标系,PROJCS则表示是平面投影坐标系
  JSONObject crsJson = new JSONObject();
  JSONObject proJson = new JSONObject();
  crsJson.put("type", "name");
  if (crs.startsWith("PROJCS")) {
  proJson.put("name", "urn:ogc:def:crs:EPSG::3857");
  crsJson.put("properties", proJson);
  } else {
  proJson.put("name", "urn:ogc:def:crs:OGC:1.3:CRS84");
  crsJson.put("properties", proJson);
  }
  geojsonObject.put("crs", crsJson);
  // itertor.close();
  long startTime = System.currentTimeMillis();
  //将json字符串使用字符流写入文件
  /* File outputfile=new File(jsonPath);
  BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(outputfile));
  bufferedWriter.write(JSON.toJSONString(geojsonObject));
  bufferedWriter.flush();
  bufferedWriter.close();*/
  File outputfile = new File(jsonPath);
  FileOutputStream fileOutputStream = new FileOutputStream(outputfile);
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
  outputStreamWriter.write(JSON.toJSONString(geojsonObject));
  outputStreamWriter.flush();
  outputStreamWriter.close();
  //将json字符串使用字节流写入文件
  /* File outputfile=new File(jsonPath);
  BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(outputfile));
  byte[] bytes= JSON.toJSONString(geojsonObject).getBytes("utf-8");
  bufferedOutputStream.write(bytes);
  //fileOutputStream.write(JSON.toJSONString(geojsonObject));
  bufferedOutputStream.flush();
  bufferedOutputStream.close();*/
  // long endTime=System.currentTimeMillis();
  // System.out.println("当前程序耗时:"+(endTime-startTime)+"ms");
  } catch (Exception e) {
  map.put("status", "failure");
  map.put("message", e.getMessage());
  e.printStackTrace();
  }
  //
  return geojsonObject;
  }
  private static String readShpContent(String shpPath, JSONArray array) {
  String fileName = "";
  try {
  FeatureJSON fjson = new FeatureJSON();
  //获取featurecollection
  File file = new File(shpPath);
  ShapefileDataStore shpDataStore = null;
  shpDataStore = new ShapefileDataStore(file.toURL());
  //设置编码
  /* Charset charset = Charset.forName("GBK");
  shpDataStore.setCharset(charset);*/
  fileName = shpDataStore.getTypeNames()[0];
  SimpleFeatureSource featureSource = null;
  featureSource = shpDataStore.getFeatureSource(fileName);
  SimpleFeatureCollection result = featureSource.getFeatures();
  SimpleFeatureIterator itertor = result.features();
  //遍历feature转为json对象
  while (itertor.hasNext()) {
  SimpleFeature feature = itertor.next();
  StringWriter writer = new StringWriter();
  fjson.writeFeature(feature, writer);
  String temp = writer.toString();
  Object geometry = JSONObject.parseObject(temp).getString(GEOMETRY);
  byte[] b = temp.getBytes("iso8859-1");
  temp = new String(b, GBK);
  JSONObject json = JSON.parseObject(temp);
  array.add(json);
  }
  itertor.close();
  } catch (Exception e) {
  e.printStackTrace();
  }
  return fileName;
  }
  /**
  * 获取Shape文件的坐标系信息,GEOGCS表示这个是地址坐标系,PROJCS则表示是平面投影坐标系
  *
  * @shpPath
  */
  public static String getCoordinateSystemWKT(String shpPath) {
  ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
  ShapefileDataStore dataStore = null;
  try {
  dataStore = (ShapefileDataStore) factory.createDataStore(new File(shpPath).toURI().toURL());
  return dataStore.getSchema().getCoordinateReferenceSystem().toWKT();
  } catch (UnsupportedOperationException | IOException e) {
  e.printStackTrace();
  } finally {
  dataStore.dispose();
  }
  return "";
  }
  /**
  * 工具类测试方法
  *
  * @param args
  */
  public static void main(String[] args) throws Exception {
  Shp2GeojsonUtils shpToGeojson = new Shp2GeojsonUtils();
  // // shape2Geojson
  String shpPath = "/Users/ecarx/Desktop/geojson/上下高架mct/123/AD_Road.shp";
  String jsonPath = "/Users/ecarx/Desktop/geojson/AD_Road.geojson";
  Map map = shpToGeojson.shp2Geojson(shpPath, jsonPath);
  // geojson2Shape
  // String shpPath = "/Users/ecarx/Desktop/geojson/上下高架mct/123/AD_Road.shp";
  // String jsonPath = "/Users/ecarx/Desktop/geojson/上下高架mct/AD_Road.geojson";
  // Map map = shpToGeojson.geoJson2Shape(jsonPath, shpPath);
  // System.out.println(map.toString());
  }
  }
  ————————————————
  版权声明:本文为CSDN博主「qiaobing1226」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
  原文链接:https://blog.csdn.net/qiaobing1226/article/details/127612665

四川启动建设423个重大项目总投资7483。7亿元图为四川省2023年第一季度重大项目现场推进活动现场。王鹏摄中新网成都1月3日电(记者王鹏)四川省2023年第一季度重大项目现场推进活动3日在成都彭州举行。记者从现场获悉,四川正式非专家建议封杀坦胸露乳的网红,让孩子的梦想回归对孩子而言,任何一个梦想并没有高低贵贱之分,如果可以的话,孩子完全可以梦的天马行空,因为每一个孩子的梦想都值得捍卫,但有些梦想真的只能是梦想。(写在前面的话)无意间在网络上看到了这华为成不了世界第一,但苹果绝对可以!文丨侠说科技华为成不了世界第一,为什么?不知道大家有没有发现一个很奇怪的现象,手中一张PPT就敢对外宣称我们是第一的基本都是中国企业,而那些外企,如美企欧企曰企韩企,他们往往特别的国内三地已监测到XBB毒株,有何症状?如何应对?近期奥密克戎新变种XBB毒株引发各方关注这种具有极高免疫逃逸能力的毒株已成为美国当前的头号流行毒株我国已至少有三地监测到XBB毒株其引发的症状有什么不同?应该如何应对?XBB免疫逃油价迎新年首涨,经济日报短期内油价将以震荡运行为主国内成品油价迎来新年首涨。据国家发展改革委消息,根据近期国际市场油价变化情况,按照现行成品油价格形成机制,自2023年1月3日24时起,国内汽柴油价格每吨分别提高250元和240元20232029全球及中国汽油凿岩机行业研究及十四五规划分析报告辰宇信息咨询市场调研公司最近发布20232029全球与中国汽油凿岩机市场调研报告内容摘要本文同时着重分析汽油凿岩机行业竞争格局,包括全球市场主要厂商竞争格局和中国本土市场主要厂商竞基金涨了也要给你浇冷水今天市场低开,三大指数都是低开,这是因为消息面的影响,消息消化了一段时间以后,就开始了震荡走高,截止中午收盘,三大指数全面翻红,上证指数收于3106。60点。整个盘面上涨3993家全国人的周口,中央为周口迁来6大总部,原驻郑州新乡安阳北京等周口,古时候称为龙都,现在是一个拥有885万常住人口的城市。2021年,周口实现GDP近3500亿元,是河南省的一个正在冉冉升起的明星城市。罗马不是一天建成的,周口的崛起也离不开中公募业绩排名大战收官近10年冠军基金年内收益均告负经济观察网记者洪小棠随着2022年悄然走过,公募基金业绩亦正式放榜。记者注意到,2022年对于主动权益基金而言,业绩分化十分明显,全年业绩首尾相差达到了98。62。整体而言,由于2必看!玩具的年龄指南,让您的孩子在玩中受益如今,我们很容易被为我们的孩子提供的玩具选择所淹没。作为一个4岁孩子的妈妈,我一直在努力寻找能让女儿开心和娱乐的玩具,同时也能为更大的目标服务并教育她。这就是为什么感官玩具可以改变RCEP生效一周年区域经济增长红利初步释放央视网消息(新闻联播)自去年1月1日区域全面经济伙伴关系协定(RCEP)正式生效以来,RCEP的15个成员中已经实施RCEP的达13个。一年来,成员国间零关税产品比例大幅提高,贸易
00后宝妈去开家长会,戴舌钉吐舌自拍惹争议,网友这不好吧随着90后逐渐成为各行各业的主力军,00后也展现自己的光芒,不再是印象中的小孩子了,甚至很多90后的孩子都能上初中了。正所谓长江后浪推前浪,前浪把后浪排在沙滩上,相比较以往的父母而绘本推荐1年味儿这是一本适合三岁以上宝宝亲子阅读的绘本。画面采用中国水墨画的风格,配以鲜艳的颜色简炼的文字,展现了过去的年代大人孩子们过年的一幕幕场景。适合培养宝宝的观察力想象力,对春节各种传统活印尼法院开始审理问题止咳糖浆案自2022年以来,印尼有数百名儿童因服用有问题的止咳糖浆不幸夭折。之后,多个受害家庭提起集体诉讼,要求讨个说法。当地时间1月17日,印尼一家法院开始审理这桩案件。26岁的苏哈迪亚蒂种族和谐,刻在新加坡骨子里的精神最近有一位刚到坡岛的妈妈在群里感叹来新加坡前,内心非常忐忑。生活在一个完全不同的城市,会有各种各样的焦虑,担心孩子会不会无法适应这里的生活,也担心自己因为外国人的身份而受到歧视,还中芯国际台积电数据出炉,外媒我们多虑了!大家都知道,全球半导体市场在2022年迎来了前所未见的寒流,在所有国家对半导体芯片需求日益增高的当下,国际芯片市场的出货量不仅没有按照预料的趋势提升,反而出现了下降的情况。对此,当韦布望远镜证实发现首颗系外行星据美国国家航空航天局(NASA)网站报道,美国科学家首次借助韦布空间望远镜证实了一颗系外行星,这颗小型岩石行星名为LHS475b,直径几乎和地球相当,距地球约41光年,位于南极座。推荐一些亲测实用的小软件第一个一罐如果你是一个有社恐的人,那么这款匿名社交软件,希望可以帮到你。在这里没有人知道你是谁,你可以放心大胆地倾诉,你可以把所有情绪都装进罐子里,抛弃所有烦恼,然后轻装前行,逐渐阿里云Centos7。6上利用docker搭建Jenkins来自动化部署Django项目一般情况下,将一个项目部署到生产环境的流程如下需求分析原型设计开发代码内网部署提交测试确认上线备份数据外网更新最终测试,如果发现外网部署的代码有异常,需要及时回滚。整个过程相当复杂AYANEOAIRPlus掌机公布搭载R76800U6英寸1080p屏IT之家1月18日消息,AYANEO今日公布了新款AIRPlus掌机,可选R76800U处理器,配备6英寸1080p屏幕。据官方介绍,AYANEOAIRPlus是目前最小的R768一图回顾2022年直播电商大事件从异军突起的东方甄选到魔性抓马的张兰俏生活,从升级全域兴趣电商的抖音电商到打出新内容战略的淘宝直播,这一年的直播电商,即有惊喜又有难题,但走向行业深水区的趋势却愈发明显。供应链内容视频配音怎么操作?怎么给自己的视频配音?配音方法分享视频配音怎么操作?手机怎么后期配音?这两天很多朋友发信息来了解配音方面的问题。那么,这个帖子就直接分享一个配音的教程吧,操作流程,挺简单的,大家不妨跟着操作一下。所需工具熊猫宝库这