GeoTools——新建shapefile文件

目录

一、引言

二、代码操作

1、服务端

2、返回数据

3、客户端

三、第二种新建shp方法

四、总结


 

 

一、引言

 

本文讲解了如何读取shp数据,如何新建shp数据,并将新建的shp数据返回到客户端进行显示。

 

 

二、代码操作

 

1、服务端

list对象是为了最后将新建的shp数据返回,pointgbk数据是源文件,pointgbkbuffer是新建文件。

    @RequestMapping("/buffer")
    @ResponseBody
    public Object buffer()
    {
        List>list=new ArrayList<>();
        long start = System.currentTimeMillis();

        String shpfile = this.getClass().getResource("/").getFile()+"file/pointgbk.shp";
        String buffile = this.getClass().getResource("/").getFile()+"file/pointgbkbuffer.shp";

        try{
            //读取shp文件
            File file = new File(shpfile);
            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();

            //创建shape文件对象
            File fileBuf = new File(buffile);
            Map params = new HashMap();
            params.put( ShapefileDataStoreFactory.URLP.key, fileBuf.toURI().toURL() );
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
            //获取原shp文件字段名
            SimpleFeatureType sft = featureSource.getSchema();
            List attrs = sft.getAttributeDescriptors();

            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            //tb.setCRS(DefaultGeographicCRS.WGS84);
            tb.setName("shapefile");
            for(int i=0;i writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);

            while (itertor.hasNext())
            {
                SimpleFeature feature = itertor.next();
                SimpleFeature featureBuf = writer.next();
                featureBuf.setAttributes(feature.getAttributes());
                //Object temp=feature.getAttribute("the_geom");
                //更新the_geom字段,改为buffer后的polygon
                Geometry geo = (Geometry)feature.getAttribute("the_geom");
                Geometry geoBuffer = geo.buffer(1.5);
                featureBuf.setAttribute("the_geom", geoBuffer);
                Map map=new HashMap<>();
                map.put("wkt",geoBuffer.toString());
                list.add(map);
            }
            writer.write();
            writer.close();
            itertor.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("共耗时"+(System.currentTimeMillis() - start)+"ms");

        return list;
    }

 

2、返回数据

[{"wkt":"POLYGON ((508930.905 299800.519, 508930.8761779206 299800.22636451694, 508930.79081929877 299799.94497485145, 508930.6522044185 299799.6856446504, 508930.4656601718 299799.4583398282, 508930.2383553496 299799.2717955815, 508929.97902514855 299799.13318070123, 508929.69763548305 299799.0478220794, 508929.405 299799.019, 508929.112364517 299799.0478220794, 508928.8309748515 299799.13318070123, 508928.5716446505 299799.2717955815, 508928.34433982824 299799.4583398282, 508928.15779558156 299799.6856446504, 508928.0191807013 299799.94497485145, 508927.93382207945 299800.22636451694, 508927.905 299800.519, 508927.93382207945 299800.811635483, 508928.0191807013 299801.0930251485, 508928.15779558156 299801.3523553495, 508928.34433982824 299801.57966017176, 508928.5716446505 299801.76620441844, 508928.8309748515 299801.9048192987, 508929.112364517 299801.99017792055, 508929.405 299802.019, 508929.69763548305 299801.99017792055, 508929.97902514855 299801.9048192987, 508930.2383553496 299801.76620441844, 508930.4656601718 299801.57966017176, 508930.6522044185 299801.3523553495, 508930.79081929877 299801.0930251485, 508930.8761779206 299800.811635483, 508930.905 299800.519))"},{"wkt":"POLYGON ((508911.3539904643 299887.2300114852, 508911.3251683849 299886.9373760022, 508911.23980976304 299886.6559863367, 508911.10119488277 299886.3966561357, 508910.9146506361 299886.16935131344, 508910.68734581384 299885.98280706676, 508910.4280156128 299885.8441921865, 508910.1466259473 299885.75883356464, 508909.8539904643 299885.7300114852, 508909.56135498127 299885.75883356464, 508909.27996531577 299885.8441921865, 508909.02063511475 299885.98280706676, 508908.7933302925 299886.16935131344, 508908.6067860458 299886.3966561357, 508908.46817116556 299886.6559863367, 508908.3828125437 299886.9373760022, 508908.3539904643 299887.2300114852, 508908.3828125437 299887.52264696825, 508908.46817116556 299887.80403663375, 508908.6067860458 299888.0633668348, 508908.7933302925 299888.290671657, 508909.02063511475 299888.4772159037, 508909.27996531577 299888.61583078397, 508909.56135498127 299888.7011894058, 508909.8539904643 299888.7300114852, 508910.1466259473 299888.7011894058, 508910.4280156128 299888.61583078397, 508910.68734581384 299888.4772159037, 508910.9146506361 299888.290671657, 508911.10119488277 299888.0633668348, 508911.23980976304 299887.80403663375, 508911.3251683849 299887.52264696825, 508911.3539904643 299887.2300114852))"},……]

 

3、客户端

使用openlayers接受并显示




    
    Title
    
    
    


GeoTools——新建shapefile文件_第1张图片

 

三、第二种新建shp方法

 

将读取出来或者新建出来的feature,变为featurecollection,使用featurestore来进行feature事务操作。

下面例子feature是从shp文件中读取的,整体写入新的shp文件

代码

   @RequestMapping("/newshp")
    @ResponseBody
    public Object newshp()
    {
        List>list=new ArrayList<>();
        String shpfile = this.getClass().getResource("/").getFile()+"file/pointgbk.shp";
        File file = new File(shpfile);
        File newFile = new File(this.getClass().getResource("/").getFile() + "file/newshp.shp");

        try {
            //读取shp文件
            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();
            //////
            //通过DataUtilities创建featuretype
            final SimpleFeatureType TYPE = DataUtilities.createType(
                    "Location",
                    "the_geom:Point:srid=4326,"
                            + // <- the geometry attribute: Point type
                            "Layer:String,"
                            + // <- a String attribute
                            "Text:String" // a number attribute
            );
            //或者通过下面方式创建featuretype,自定义方式
/*            SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
            builder.setName("Location");
            builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
            // add attributes in order
            builder.add("the_geom", Point.class);
            builder.length(15).add("Name", String.class); // <- 15 chars width for name field
            builder.add("number", Integer.class);
            // build the type
            final SimpleFeatureType LOCATION = builder.buildFeatureType();*/
            //准备shp中的feature,存入list中
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
            List features = new ArrayList<>();
            SimpleFeatureIterator itertor2 = result.features();
            while (itertor2.hasNext()) {
/*                SimpleFeature feature = itertor2.next();
                Geometry geo = (Geometry) feature.getAttribute("the_geom");
                featureBuilder.add(geo);
                featureBuilder.add("namename");
                SimpleFeature tempfeature = featureBuilder.buildFeature(null);
                features.add(tempfeature);*/
                SimpleFeature feature = itertor2.next();
                features.add(feature);
            }

            //创建新shp文件
            ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
            Map params2 = new HashMap<>();
            params2.put("url", newFile.toURI().toURL());
            params2.put("create spatial index", Boolean.TRUE);
            ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params2);
            newDataStore.createSchema(TYPE);
            //将feature数组写入featuresource
            Transaction transaction = new DefaultTransaction("create");
            String typeName2 = newDataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource2 = newDataStore.getFeatureSource(typeName2);
            SimpleFeatureType SHAPE_TYPE = featureSource2.getSchema();
            /*
             * The Shapefile format has a couple limitations:
             * - "the_geom" is always first, and used for the geometry attribute name
             * - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon
             * - Attribute names are limited in length
             * - Not all data types are supported (example Timestamp represented as Date)
             *
             * Each data store has different limitations so check the resulting SimpleFeatureType.
             */
            if (featureSource2 instanceof SimpleFeatureStore) {
                SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource2;
                /*
                 * SimpleFeatureStore has a method to add features from a
                 * SimpleFeatureCollection object, so we use the ListFeatureCollection
                 * class to wrap our list of features.
                 */
                SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
                featureStore.setTransaction(transaction);
                try {
                    featureStore.addFeatures(collection);
                    transaction.commit();
                } catch (Exception problem) {
                    problem.printStackTrace();
                    transaction.rollback();
                } finally {
                    transaction.close();
                    itertor2.close();
                }
                //System.exit(0); // success!
            } else {
                System.out.println(typeName + " does not support read/write access");
                System.exit(1);
            }
        }catch (Exception e)
        {
            e.getMessage();
        }
        return 1;

    }

 

 

四、总结

 

  • 读取shp文件;

 

  • 获取要素信息;

 

  • 新建shp文件两种方法;

 

 

你可能感兴趣的:(GIS)