读写shp等空间数据,进行geometry、SimpleFeature等转换的工具类

32 篇文章 45 订阅
这个Java类库提供了对GeoTools、GeoJSON和Shapefile数据的读取、转换和过滤功能。它能够将多边形、多线串和多点几何对象分解为简单几何对象,支持从Shapefile和GeoJSON文件读取几何特征,并能将数据写入Shapefile和GeoJSON格式。此外,还包含了一个用于过滤线串长度的方法。
摘要由CSDN通过智能技术生成

直接上代码


import org.geotools.data.*;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geojson.GeoJSONUtil;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class RwUtils {
    private static Logger logger = LoggerFactory.getLogger(RwUtils.class);

    public static List<? extends Geometry> toSimple(List<? extends Geometry> geometryList) {
        List< Geometry> simpleLineList = new ArrayList<>();
        for (Geometry geometry : geometryList) {
            if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {
                for (int j = 0; j < geometry.getNumGeometries(); j += 1) {
                    simpleLineList.add(geometry.getGeometryN(j));
                }
            } else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {
                simpleLineList.add(geometry);
            }
        }
        return simpleLineList;
    }

    public static List<SimpleFeature> toSimpleFeature(List<SimpleFeature> simpleFeatureList){
        List<SimpleFeature> resultList = new ArrayList<>();
        for (SimpleFeature simpleFeature: simpleFeatureList) {
            Geometry geometry = (Geometry) simpleFeature.getDefaultGeometry();
            if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {
                for (int i = 0; i < geometry.getNumGeometries(); i += 1) {
                    SimpleFeature clone = SimpleFeatureBuilder.deep(simpleFeature);
                    clone.setDefaultGeometry(geometry.getGeometryN(i));
                    resultList.add(clone);
                }
            } else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {
                resultList.add(simpleFeature);
            }
        }
        return resultList;
    }


    public static List<LineString> toSimpleLine(List<? extends Geometry> geometryList) {
        List<LineString> simpleLineList = new ArrayList<>();
        for (Geometry geometry : geometryList) {
            if (geometry instanceof MultiLineString) {
                for (int j = 0; j < geometry.getNumGeometries(); j += 1) {
                    simpleLineList.add((LineString) geometry.getGeometryN(j));
                }
            } else if (geometry instanceof LineString) {
                simpleLineList.add((LineString) geometry);
            }
        }
        return simpleLineList;
    }

    public static List<Geometry>  readFeaturesShp(String path){
        List<Geometry> geometryList = new ArrayList<>();
        try {
            File file = new File(path);
            Map<String, Object> map = new HashMap<>();
            map.put("url", file.toURI().toURL());
            DataStore dataStore = DataStoreFinder.getDataStore(map);
            String typeName = dataStore.getTypeNames()[0];
            FeatureSource<SimpleFeatureType, SimpleFeature> source =
                    dataStore.getFeatureSource(typeName);
//            Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")
            geometryList = new ArrayList<>();
            FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
//            features = collection.features();
//            dataStore.dispose();
            try (FeatureIterator<SimpleFeature> features = collection.features()) {
                while (features.hasNext()) {
                    SimpleFeature feature = features.next();
                    Geometry geomrtry = (Geometry)feature.getDefaultGeometry();
                    geometryList.add(geomrtry);
                }
                features.close();
                dataStore.dispose();
            }
        }catch (Exception e){
            System.out.println(e);
        }

        return geometryList;
    }

    public static List<LineString>  readCenterLineFeaturesShp(String path){

        List<Geometry> geometryList = readFeaturesShp(path);
        return toSimpleLine(geometryList);
    }

    public static List<Geometry> readGeoJson(String geojsonPath){
        List<Geometry> geometryList = new ArrayList<>();
        InputStreamReader reader = null;
        try{
            reader = new InputStreamReader(new FileInputStream(geojsonPath), "UTF-8");
            FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
            geometryList = new ArrayList<>();
            while (features.hasNext()) {
                SimpleFeature feature = features.next();
                Geometry line = (Geometry) feature.getDefaultGeometry();
                geometryList.add(line);
            }

        }catch (Exception e){
            logger.error("=======================读取异常:" + e);
        }finally {
            try {
                assert reader != null;
                reader.close();
            }catch (Exception e){
                logger.error("=======================读取流关闭异常:" + e);
            }
        }
        return geometryList;
    }


    public static List<LineString> readCenterLine(String path){
        List<LineString> centerLineList = new ArrayList<>();
        InputStreamReader reader = null;
        try{
            reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
            FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
            List<Geometry> centerGeomList = new ArrayList<>();
            while (features.hasNext()) {
                SimpleFeature feature = features.next();
                Geometry line = (Geometry) feature.getDefaultGeometry();
                centerGeomList.add(line);
            }
            centerLineList = toSimpleLine(centerGeomList);
        }catch (Exception e){
            logger.error("=======================读取异常:" + e);
        }finally {
            try {
                assert reader != null;
                reader.close();
            }catch (Exception e){
                logger.error("=======================读取流关闭异常:" + e);
            }
        }
        return centerLineList;
    }


    public static List<SimpleFeature> readCenterLineFeatures(String path){
        List<SimpleFeature> featureList = new ArrayList<>();
        InputStreamReader reader = null;
        try{
            reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
            FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
            while (features.hasNext()) {
                SimpleFeature feature = features.next();
                featureList.add(feature);
            }
        }catch (Exception e){
            logger.error("=======================读取异常:" + e);
        }finally {
            try {
                assert reader != null;
                reader.close();
            }catch (Exception e){
                logger.error("=======================读取流关闭异常:" + e);
            }
        }
        return featureList;
    }



    public static void featureToShp(String path, List<SimpleFeature> outFeatures){
        try {
            FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
            File file = new File(path);
            if (file.exists()) {
                return;
            }
            Map map = Collections.singletonMap("url", file.toURI().toURL());
            ShapefileDataStore dataStore = (ShapefileDataStore)factory.createNewDataStore(map);
            SimpleFeatureType featureType =outFeatures.get(0).getType();
            dataStore.createSchema(featureType);
            dataStore.forceSchemaCRS(CRS.decode("EPSG:3857"));

            /*
             * Write the features to the shapefile
             */
            Transaction transaction = new DefaultTransaction("create");

            String typeName = dataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);

            if (featureSource instanceof SimpleFeatureStore) {
                SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
                SimpleFeatureCollection collection = new ListFeatureCollection(featureType, outFeatures);
                featureStore.setTransaction(transaction);
                try {
                    featureStore.addFeatures(collection);
                    transaction.commit();
                } catch (Exception problem) {
                    problem.printStackTrace();
                    transaction.rollback();
                } finally {
                    transaction.close();
                }
//                System.exit(0); // success!
            } else {
                System.out.println(typeName + " does not support read/write access");
//                System.exit(1);
            }
        }catch (Exception e){
            System.out.println(e);
        }

    }


    public static void featureToGeojson(String path, List<SimpleFeature> outFeatures){
        Writer gjsonWriter = null;
        try{
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            if (outFeatures.isEmpty()) {
                return;
            }
            FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(6));
//            CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:3857");
            gjsonWriter = new OutputStreamWriter(new FileOutputStream(singleRoadPath), StandardCharsets.UTF_8);
//            featureJSON.writeCRS(sourceCRS,gjsonWriter);
            featureJSON.writeFeatureCollection(new ListFeatureCollection(outFeatures.get(0).getType(), outFeatures), gjsonWriter);

        }catch (Exception e){
            logger.error("=======================feature写入异常:" + e);
        }finally {
            try{
                if (gjsonWriter != null) {
                    gjsonWriter.flush();
                    gjsonWriter.close();
                }
            }catch (IOException ie){
                logger.error("=======================流关闭异常:" + ie);
            }
        }
    }
    public static List<SimpleFeature> geometrysToGeojson( List<? extends Geometry> lineStringList, String lineType){
        List<SimpleFeature> lineFeatures = new ArrayList<>();
        try {
            SimpleFeatureType type = DataUtilities.createType("line", lineType);
            SimpleFeatureBuilder linefeatureBuilder = new SimpleFeatureBuilder(type);
            linefeatureBuilder.add("id");
            for (int i = 0; i < lineStringList.size(); i++) {
                Geometry centerLine = lineStringList.get(i);
                if(centerLine == null){
                    continue;
                }

                //linefeatureBuilder.set("id", String.valueOf(i));

                SimpleFeature featureLine = linefeatureBuilder.buildFeature(String.valueOf(i));
                featureLine.setDefaultGeometry(centerLine);
                featureLine.setAttribute("id",String.valueOf(i));
                lineFeatures.add(featureLine);
            }
        }catch (Exception e){
            logger.error("异常:" + e);
        }
        return lineFeatures;
    }

    public static void geometrysToGeojson(String output, List<? extends Geometry> lineStringList, String lineType){
        List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);
        featureToGeojson(output, lineFeatures);
    }

    public static void geometrysToShp(String output, List<? extends Geometry> lineStringList, String lineType){
        List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);
        featureToShp(output, lineFeatures);
    }

    public static List<LineString> filterLinesByLen(List<LineString> simpleLineList, float filterLen){
        List<LineString> filterLineList = new ArrayList<>();
        for (LineString simpleLine: simpleLineList) {
            if(simpleLine.getLength() >= filterLen){
                filterLineList.add(simpleLine);
            }
        }
        return filterLineList;
    }

}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二十同学

谢谢大佬打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值