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<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.length();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();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章