shape文件的操作

一、maven依赖引入

<dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-api</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-pool</groupId>
                    <artifactId>commons-pool</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>jgridshift</groupId>
                    <artifactId>jgridshift</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>Javax.media</groupId>
                    <artifactId>jai_core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>
        <dependency>
            <groupId>jgridshift</groupId>
            <artifactId>jgridshift</artifactId>
        </dependency>
        <dependency>
            <groupId>Javax.media</groupId>
            <artifactId>jai_core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hsqldb</groupId>
                    <artifactId>hsqldb</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hsqldb/hsqldb -->
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
        </dependency>

备注:需要配置下载org.geotools的私有仓库

<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>
    </repositories>

二、读取shape文件,并转换为对象T

 public  static List<T>readShape(URL url) throws IOException {
        ShapefileDataStore store = new ShapefileDataStore(url);
        //设置编码
        Charset charset = Charset.forName("GBK");
        store.setCharset(charset);
        SimpleFeatureSource sfSource = store.getFeatureSource();
        SimpleFeatureIterator sfIter = sfSource.getFeatures().features();
        // 从ShapeFile文件中遍历每一个Feature,然后将Feature转为GeoJSON字符串
        List<T> list = new ArrayList<>();
        while (sfIter.hasNext()) {
            SimpleFeature feature = sfIter.next();
            // Feature转GeoJSON
            FeatureJSON fjson = new FeatureJSON();
            StringWriter writer = new StringWriter();
            fjson.writeFeature(feature, writer);
            JSONObject jsonObject = new JSONObject(writer.toString());
            String type = jsonObject.getStr("type").toLowerCase();
            if (type.equals("multipolygon")){
                LOGGER.error("该数据不是图斑:【{}】",writer);
                continue;
            }
            String properties = jsonObject.remove("properties").toString();
            jsonObject.remove("id");
            //其他属性
            T t = JSONUtil.toBean(properties, T.class);
            if (JudgeUtil.isDBNull(t.getObjectid())){
                LOGGER.error("该图斑每页objectid:【{}】",writer.toString());
                continue;
            }
            //geojson
            t.setGeojson(jsonObject.toString());

            list.add(gisWarnQrstbhhx);
        }
        return list;
    }

三、shape文件写入

1、写入shape文件入口

 /**
     * 写shape文件
     * @param rootFile
     * @param shapeName shape文件名 包含后缀名.shp
     * @param list
     */
    public static  void writeShape(File rootFile,String shapeName,List<T>list) throws IOException {
        if (JudgeUtil.isEmpty(list)){
            throw new WrongDataException("数据不能为空");
        }
        String  type = new JSONObject(list.get(0).getGeojson()).getStr("type").toLowerCase();
        //将list转换为geoJson字符串
        String geoJson = getGsoJson(list);
        if (!rootFile.exists() || rootFile.isFile()){
            rootFile.mkdirs();
        }
        File file = new File(rootFile,shapeName);
        Map<String, Serializable> params = new HashMap<>();
        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.setDefaultGeometry("the_geom");

        //添加属性
        addProperties(type,tb);

        ds.createSchema(tb.buildFeatureType());
        //设置编码
        Charset charset = Charset.forName("GBK");
        ds.setCharset(charset);
        FeatureJSON featureJson = new FeatureJSON();
        SimpleFeatureCollection featureCollection = (SimpleFeatureCollection) featureJson.readFeatureCollection(geoJson);
        FeatureIterator<SimpleFeature> iterator = featureCollection.features();
        //设置Writer
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        //写下一条
        SimpleFeature srcFeature;
        Iterator<Property> properties;
        while (iterator.hasNext()){
            srcFeature = iterator.next();
            properties = srcFeature.getProperties().iterator();
            SimpleFeature  destFeature = writer.next();

            while (properties.hasNext()){
                Name name = properties.next().getName();
                Object attribute = srcFeature.getAttribute(name);
                if (!(attribute instanceof Geometry)){
                    destFeature.setAttribute(name, attribute);
                }
            }
            destFeature.setDefaultGeometryProperty(srcFeature.getDefaultGeometryProperty());
        }
        writer.write();
        writer.close();
        ds.dispose();
    }

2、将List<T>转换为geojson

/**
     * T转geojson
     * @param list
     * @return
     */
    private static String getGsoJson(List<T>list){
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("type","FeatureCollection");

        JSONArray jsonArray = new JSONArray();
        jsonObject.putOnce("features",jsonArray);
        for (T t : list) {
            JSONObject feature = new JSONObject();
            feature.putOnce("type","Feature");
            feature.putOnce("geometry",new JSONObject(t.getGeojson()));
            t.setGeojson(null);
            t.setGeom(null);
            t.setGid(null);
            feature.putOnce("properties",JSONUtil.parseObj(t));
            jsonArray.add(feature);
        }
        return jsonObject.toString();
    }

3、通过反射 添加properties

/**
     * 通过反射 添加properties
     * @param tb
     */
    private static void addProperties(String type, SimpleFeatureTypeBuilder tb){
        Field[] declaredFields = T.class.getDeclaredFields();
        setType(tb,type.toLowerCase());
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            if (!name.equals("serialVersionUID") && !name.equals("geojson") && !name.equals("geom")){
                tb.add(name,declaredField.getType());
            }
        }
    }

4、设置类型

private static void setType(SimpleFeatureTypeBuilder tb,String type){
        if (type.equals("point")) {
            tb.add("the_geom", Point.class);
        } else if (type.equals("line")) {
            tb.add("the_geom", LineString.class);
        } else if (type.equals("polygon")) {
            tb.add("the_geom", Polygon.class);
        } else if (type.equals("multipoint")) {
            tb.add("the_geom", MultiPoint.class);
        } else if (type.equals("multiline")) {
            tb.add("the_geom", MultiLineString.class);
        } else if (type.equals("multipolygon")) {
            tb.add("the_geom", MultiPolygon.class);
        }
    }

 

posted @ 2020-09-25 15:59  炫舞风中  阅读(481)  评论(0编辑  收藏  举报