GeoTools——shp转geojson

目录

一、引言

二、代码操作

1、服务端

2、返回数据

三、总结


 

一、引言

 

数据库中经常存储的格式是符合OGC标准的WKT或WKB,而在网络中经常传输的格式是json,因此我们会经常把各种数据转为geojson的形式以服务形式发出,供客户端使用。当然你硬要用wkt格式也行,没人管你,自己知道就ok,由于涉及到属性数据只是建议geojson比较方便,毕竟WFS也是用的geojson返回的==

 

 

二、代码操作

 

1、服务端

读取shp数据,解析出simplefeature,使用featurejson转化为json,然后拼接输出。

 /**
     * 后台将shp数据转为geojson,返回
     * @return
     */
    @RequestMapping("/geojson")
    @ResponseBody
    public Object shp2geojson()
    {

        String shpPath=this.getClass().getResource("/").getFile()+"/file/pointgbk.shp";
        String  jsonPath=this.getClass().getResource("/").getFile()+"file/point.geojson";
        Map map = new HashMap();
        //新建json对象
        FeatureJSON fjson = new FeatureJSON();
        JSONObject geojsonObject=new JSONObject();
        geojsonObject.put("type","FeatureCollection");
        try{
            //获取featurecollection
            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();
            //遍历feature转为json对象
            while (itertor.hasNext())
            {
                SimpleFeature feature = itertor.next();
                StringWriter writer = new StringWriter();
                fjson.writeFeature(feature, writer);
                String temp=writer.toString();
                byte[] b=temp.getBytes("iso8859-1");
                temp=new String(b,"gbk");
                System.out.println(temp);
                JSONObject json =  JSON.parseObject(temp);
                array.add(json);
            }
            geojsonObject.put("features",array);
            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;
    }

 

2、返回数据

{"features":[{"geometry":{"coordinates":[508909.854,299887.23],"type":"Point"},"id":"pointgbk.2","type":"Feature","properties":{"ExtendedEn":"{ 83103 } { L31-20201081-24 L31-20201081-24 }","SubClasses":"AcDbEntity:AcDbText:AcDbText","EntityHand":"1522","Text":"37.24","Linetype":"","Layer":"文字层组-标注"}},{"geometry":{"coordinates":[508884.9711,299895.6874],"type":"Point"},"id":"pointgbk.3","type":"Feature","properties":{"ExtendedEn":"{ 83103 } { L31-20201081-25 L31-20201081-25 }","SubClasses":"AcDbEntity:AcDbText:AcDbText","EntityHand":"1523","Text":"37.23","Linetype":"","Layer":"文字层组-标注"}},……],"type":"FeatureCollection"}

 

 

三、总结

 

  • 使用wkt与geojson;

 

  • 代码操作将shp中的feature转化为geojson;

 

补充:

geojson转shp

		Map map = new HashMap();
		GeometryJSON gjson = new GeometryJSON();
		try{
			String strJson = cm.getFileContent(jsonPath);
			JSONObject json = new JSONObject(strJson);
			JSONArray features = (JSONArray) json.get("features");
			JSONObject feature0 = new JSONObject(features.get(0).toString());
			System.out.println(feature0.toString());
			String strType = ((JSONObject)feature0.get("geometry")).getString("type").toString();
			
			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 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.add("the_geom", geoType);
			tb.add("POIID", Long.class);
			ds.createSchema(tb.buildFeatureType());
			//设置编码
            Charset charset = Charset.forName("GBK");
            ds.setCharset(charset);
			//设置Writer
			FeatureWriter writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
			
			for(int i=0,len=features.length();i

 

你可能感兴趣的:(GIS)