shp转换为Geojson

 public static String toGeoJson(String shpPath) throws IOException, JSONException {
        Map map = new HashMap();
        FeatureJSON fjson = new FeatureJSON(new GeometryJSON(20));
        File file = new File(shpPath);

/*            String fileNameFull = file.getName();
            String[] strAry = fileNameFull.split("\\.");
            String suffix = strAry[1];
            String fileName = strAry[0]; */
        StringBuffer sb = new StringBuffer();
        sb.append("{\"type\": \"FeatureCollection\",\"features\": ");
        ShapefileDataStore shpDataStore = null;

        shpDataStore = new ShapefileDataStore(file.toURL());
        //设置编码
        Charset charset = Charset.forName("GBK");
        shpDataStore.setStringCharset(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();
        while (itertor.hasNext()) {
            SimpleFeature feature = itertor.next();
            StringWriter writer = new StringWriter();
            fjson.writeFeature(feature, writer);
            JSONObject json = (JSONObject) JSON.parse(writer.toString());
            array.add(json);
        }
        itertor.close();
        sb.append(array.toString());
        sb.append("}");
        return sb.toString();
    }

你可能感兴趣的:(java)