GeoTools——shp转geojson

本文介绍了如何使用GeoTools库将Shapefile格式的数据转换为GeoJSON,包括服务端读取Shapefile,解析成SimpleFeature,再转换成JSON格式的过程,以及返回的GeoJSON数据示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、引言

二、代码操作

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;
            featureSo