shp文件和geojson实现互转


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vividsolutions.jts.geom.*;
import lombok.extern.slf4j.Slf4j;
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 java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ShpUtils {

  /**
   * geojson转换为shp文件
   * @param jsonPath
   * @param shpPath
   * @return
   */
  public static Map geojson2Shape(String jsonPath, String shpPath) {
    Map map = new HashMap();
    GeometryJSON gjson = new GeometryJSON();
    try {
      String strJson = new String(FileUtil.getBytes(jsonPath));
      JSONObject json = JSONObject.parseObject(strJson);
      JSONArray features = (JSONArray) json.get("features");
      JSONObject feature0 = JSONObject.parseObject(features.get(0).toString());
      System.out.println(feature0.toString());
      String strType = ((JSONObject) feature0.get("geometry")).getString("type");

      Class<?> geoType = null;
      switch (strType) {
        case "Point":
          geoType = Point.class;
        case "MultiPoint":
          geoType = MultiPoint.class;
        case "LineString":
          geoType = LineString.class;
        case "MultiLineString":
          geoType = MultiLineString.class;
        case "Polygon":
          geoType = Polygon.class;
        case "MultiPolygon":
          geoType = MultiPolygon.class;
      }
      //创建shape文件对象
      File file = new File(shpPath);
      Map<String, Serializable> params = new HashMap<String, Serializable>();
      params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
      ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
      //定义图形信息和属性信息
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.setCRS(DefaultGeographicCRS.WGS84);
      tb.setName("shapefile");
      tb.add("the_geom", geoType);
      tb.add("POIID", Long.class);
      ds.createSchema(tb.buildFeatureType());
      //设置编码
      Charset charset = Charset.forName("GBK");
      ds.setCharset(charset);
      //设置Writer
      FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.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();
        feature.setAttribute("the_geom", gjson.readMultiPolygon(reader));
        feature.setAttribute("POIID", i);
        writer.write();
      }
      writer.close();
      ds.dispose();
      map.put("status", "success");
      map.put("message", shpPath);
    } catch (Exception e) {
      map.put("status", "failure");
      map.put("message", e.getMessage());
      e.printStackTrace();
    }
    return map;
  }

  /**
   * geojson转换为shp文件
   * @param json
   * @param shpPath
   * @return
   */
  public static Map geojson2Shape2(String json, String shpPath) {
    Map map = new HashMap();
    GeometryJSON gjson = new GeometryJSON();
    try {
      JSONObject jsonObject = JSONObject.parseObject(json);
      JSONArray features = (JSONArray) jsonObject.get("features");
      JSONObject feature0 = JSONObject.parseObject(features.get(0).toString());
      System.out.println(feature0.toString());
      String strType = ((JSONObject) feature0.get("geometry")).getString("type");

      Class<?> geoType = null;
      switch (strType) {
        case "Point":
          geoType = Point.class;
        case "MultiPoint":
          geoType = MultiPoint.class;
        case "LineString":
          geoType = LineString.class;
        case "MultiLineString":
          geoType = MultiLineString.class;
        case "Polygon":
          geoType = Polygon.class;
        case "MultiPolygon":
          geoType = MultiPolygon.class;
      }
      //创建shape文件对象
      File file = new File(shpPath);
      Map<String, Serializable> params = new HashMap<String, Serializable>();
      params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
      ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
      //定义图形信息和属性信息
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.setCRS(DefaultGeographicCRS.WGS84);
      tb.setName("shapefile");
      tb.add("the_geom", geoType);
      tb.add("POIID", Long.class);
      ds.createSchema(tb.buildFeatureType());
      //设置编码
      Charset charset = Charset.forName("GBK");
      ds.setCharset(charset);
      //设置Writer
      FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.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();
        feature.setAttribute("the_geom", gjson.readMultiPolygon(reader));
        feature.setAttribute("POIID", i);
        writer.write();
      }
      writer.close();
      ds.dispose();
      map.put("status", "success");
      map.put("message", shpPath);
    } catch (Exception e) {
      map.put("status", "failure");
      map.put("message", e.getMessage());
      e.printStackTrace();
    }
    return map;
  }
  /**
   * shp转换为Geojson
   * @param shpPath
   * @return
   */
  public static Map shape2Geojson(String shpPath, String jsonPath, String jsonName) {
    Map map = new HashMap();
    FeatureJSON fjson = new FeatureJSON();
    try {
      StringBuffer sb = new StringBuffer();
      sb.append("{\"type\": \"FeatureCollection\",\"features\": ");

      File file = new File(shpPath);
      ShapefileDataStore shpDataStore = null;

      shpDataStore = new ShapefileDataStore(file.toURL());
      //设置编码
      Charset charset = Charset.forName("GBK");
      shpDataStore.setCharset(charset);
      String typeName = shpDataStore.getTypeNames()[0];
      SimpleFeatureSource featureSource = null;
      featureSource = shpDataStore.getFeatureSource(typeName);
      SimpleFeatureCollection result = featureSource.getFeatures();
      SimpleFeatureIterator itertor = result.features();
      JSONArray array = new JSONArray();
      while (itertor.hasNext()) {
        SimpleFeature feature = itertor.next();
        StringWriter writer = new StringWriter();
        fjson.writeFeature(feature, writer);
        JSONObject json = JSONObject.parseObject(writer.toString());
        array.add(json);
      }
      itertor.close();
      sb.append(array);
      sb.append("}");

      //写入文件
      FileUtil.getFile(sb.toString().getBytes(StandardCharsets.UTF_8), jsonPath, jsonName);

      map.put("status", "success");
      map.put("message", sb.toString());
    } catch (Exception e) {
      map.put("status", "failure");
      map.put("message", e.getMessage());
      e.printStackTrace();

    }
    return map;
  }

  /**
   * 工具类测试方法
   * @param args
   */
  public static void main(String[] args){
    String shpPath = "D:\\test_jhp\\app2\\vf_slu_0.shp";
    String jsonPath = "D:\\test_jhp\\app2\\";
    Map map = ShpUtils.shape2Geojson(shpPath, jsonPath, "test.json");

    int i = 0;
//		String shpPath = "D:/data/beijing/China43262.shp";
//		String jsonPath = "D:/data/beijing/China4326.geojson";
//		Map map = fileFormat.geojson2Shape(jsonPath, shpPath);
  }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值