java使用GeoTools,JTS实现叠加分析、提取分析、近邻分析

简介

概念:
JTS:JTS Topology Suite (JTS)是一个开源的Java软件库,它提供了平面几何的对象模型和基本的几何函数,符合OGC发布的“Simple Features for SQL”(SFSQL)规范。JTS被设计用作基于矢量地理信息软件的核心组件,还可以用作计算几何的通用算法库。

GeoTools:GeoTools 是一个开源 (LGPL) Java 代码库,它为操作地理空间数据提供符合标准的方法,例如实现地理信息系统。GeoTools 库数据结构基于开放地理空间联盟 (OGC) 规范。
官网地址:
https://www.geotools.org/

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

数据操作

  1. **shape
public static void readShpFile(String shpPath) {
       File shpFile = new File(shpPath);
       try {
           ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpFile.toURI().toURL());
           // 设置编码,防止属性的中文字符出现乱码
           shapefileDataStore.setCharset(Charset.forName("UTF-8"));
           // 这个typeNamae不传递,默认是文件名称
           FeatureSource featuresource = shapefileDataStore.getFeatureSource(shapefileDataStore.getTypeNames()[0]);
           // 读取bbox
           ReferencedEnvelope bbox  =featuresource.getBounds();
           // 读取投影
           CoordinateReferenceSystem crs = featuresource.getSchema().getCoordinateReferenceSystem();
           // 特征总数
           int count = featuresource.getCount(Query.ALL);
           // 获取当前数据的geometry类型(点、线、面)
           GeometryType geometryType = featuresource.getSchema().getGeometryDescriptor().getType();
           // 读取要素
           SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featuresource.getFeatures();
           // 获取当前矢量数据有哪些属性字段值
           List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
           // 拿到迭代器
           SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
           // 遍历每一个要素
           while(simpleFeatureIterator.hasNext()) {
               SimpleFeature simpleFeature = simpleFeatureIterator.next();
               // java8新特性流api
               attributes.stream().forEach((a) -> {
                   // 依次读取这个shape中每一个属性值,当然这个属性值,可以处理其它业务
                   System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));
               });
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
       System.out.println("读取完成!");
   }

2. Geoserver服务数据读取

    public static final String getFeatureApi = "{{url}}/geoserver/wfs?service=wfs&version=2.0.0&outputFormat=application/json&request=GetFeature&typeNames={{workspace}}:{{layerName}}";
        /**
     * 获取SimpleFeatureCollection
     */
    public static SimpleFeatureCollection getFeature(
            String url,
            String username,
            String password,
            String workspace,
            String layerName) {
        try {
            String urlStr = buildUrl(getFeatureApi, url, workspace, layerName);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            HttpGet httpGet = new HttpGet(urlStr);
            HttpResponse response = httpClient.execute(httpGet);
            String jsonStr = EntityUtils.toString(response.getEntity());
            ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
            return (SimpleFeatureCollection) new FeatureJSON().readFeatureCollection(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

3. wkt数据读取

// ex : MultiPolygon ( ((10 10, 10 20, 20 20, 20 15, 10 10)), ((60 60, 70 70, 80 60, 60 60 )) )
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(wktStr);

4. geojson读取

//{“type”:“Feature”,“crs”:{“type”:“name”,“properties”:{“name”:“EPSG:2380”}},“geometry”:{“type”:“MultiPolygon”,“coordinates”:[[[[646398.9535,3267941.9664],[649558.7196,3267895.3528],[649674.763,3265683.4124],[646387.8773,3265827.4858],[646398.9535,3267941.9664]]]]},“properties”:{“Id”:0}}
public static void readGeoJson(String jsonPath) throws IOException {
       File file = new File(jsonPath);
       FileInputStream fileInputStream = new FileInputStream(file);
       // 这里可能存在问题,如果是超大文件怎么办,一次性读入会不会报内存
       // 解决方案是不是对大文件进行拆分
       GeoJSONReader geoJSONReader = new GeoJSONReader(fileInputStream);
       SimpleFeatureCollection featureCollection = geoJSONReader.getFeatures();
       SimpleFeatureIterator iterator = featureCollection.features();
       List<AttributeDescriptor> attributes = featureCollection.getSchema().getAttributeDescriptors();
       while (iterator.hasNext()) {
           SimpleFeature simpleFeature = iterator.next();
           System.out.println();
           attributes.stream().forEach((a) -> {
               // 依次读取这个shape中每一个属性值,当然这个属性值,可以处理其它业务
               System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));
           });
       }
       fileInputStream.close();
       System.out.println("读取JSON完毕!");
   }

5. 遍历要素及属性

SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featuresource.getFeatures();
// 获取当前矢量数据有哪些属性字段值
List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
// 拿到迭代器
SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
// 遍历每一个要素
while(simpleFeatureIterator.hasNext()) {
   SimpleFeature simpleFeature = simpleFeatureIterator.next();
   // java8新特性流api
   attributes.stream().forEach((a) -> {
       // 依次读取这个shape中每一个属性值,当然这个属性值,可以处理其它业务
       //Object jzmcValue = feature.getAttribute("jzmc");
       System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));
   });
}

6.新增要素(创建图层)

//1.构造TYPE(定义数据的坐标参考、属性字段)
//Class的取值可以是:几何(Point.class,Polygon.class,MultiPolygon.class),属性(String.class,Integer.class, Double.class)
public static SimpleFeatureType createType(Class<?> c, String layerName) {
     SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
     builder.setCRS(DefaultGeographicCRS.WGS84);
     builder.add("FID",String.class);
     // 需要注意的是几何字段的属性名称是固定的
     builder.add("the_geom", c);
     // 设置了图层的名字
     builder.setName(layerName);
     SimpleFeatureType simpleFeatureType = builder.buildFeatureType();
     return simpleFeatureType;
 }
 
 //2.根据TYPE构建单个要素
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(simpleFeatureType);
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(wktStr);
// 这里的添加顺序和上面TYPE的时候保持一致
featureBuilder.add("1");
featureBuilder.add(geometry);
SimpleFeature feature = featureBuilder.buildFeature(null);

//3.创建FeatureCollection
List<SimpleFeature> features = new ArrayList<>();
 // 只需要将上面步骤的单个要素放入循环中创建更多的要素
 features.add(feature);
 SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
 
 //4. 生成shpfile
File shpFile = new File(shpPath);
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
// 创造shpstore需要的参数
Map<String, Serializable> params = new HashMap<>();
params.put("url", shpFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(simpleFeatureType);
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
SimpleFeatureCollection collection = new ListFeatureCollection(simpleFeatureType, features);
featureStore.setTransaction(transaction);
featureStore.addFeatures(collection);
featureStore.setTransaction(transaction);
transaction.commit();
transaction.close();

7.读取TIFF

public static Coverage readTiff(String tiffPath) throws IOException {
     File f = new File(tiffPath);
     ParameterValue<OverviewPolicy> policy = AbstractGridFormat.OVERVIEW_POLICY.createValue();
     policy.setValue(OverviewPolicy.IGNORE);
     ParameterValue<String> gridsize = AbstractGridFormat.SUGGESTED_TILE_SIZE.createValue();
     ParameterValue<Boolean> useJaiRead = AbstractGridFormat.USE_JAI_IMAGEREAD.createValue();
     useJaiRead.setValue(true);
     GridCoverage2D image = new GeoTiffReader(f).read(new GeneralParameterValue[]{policy, gridsize, useJaiRead});
     return image;
 }

生成TIFF

File file = new File(outTiffPath);
GeoTiffWriter geoTiffWriter = new GeoTiffWriter(file);
final GeoTiffFormat format = new GeoTiffFormat();
final GeoTiffWriteParams wp = new GeoTiffWriteParams();
// 设置写出参数
wp.setCompressionMode(GeoTiffWriteParams.MODE_DEFAULT);
wp.setTilingMode(GeoToolsWriteParams.MODE_DEFAULT);
ParameterValueGroup paramWrite = format.getWriteParameters();
paramWrite.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);
geoTiffWriter.write((GridCoverage) coverage, paramWrite.values().toArray(new GeneralParameterValue[4]) );
geoTiffWriter.dispose();

空间分析

空间关系(Geometry Relationships):
常见的空间关系(Geometry Relationships)包括:Disjoint、Intersects、Touches、Crosses、Within、Contains、Overlaps、Relates。

空间操作(Geometry Operations):
常见的空间操作(Geometry Operations)包括:Buffer、Intersection、ConvexHull、Intersection、Union、Difference、SymDifference。

裁剪

    /**
     * 裁剪
     *
     **/
    public static  List<String>  newClip(GeoserverAnalysisClipDTO dto) {
        //获取服务数据
        SimpleFeatureCollection collection = GeoServerAnalysisUtils.getFeature(dto.getGeoserverUrl(), dto.getUsername(), dto.getPassword(), dto.getWorkspace(), dto.getLayerName());

        // 要裁剪的几何形状
        Geometry clipGeometry = SpatialAnalysisUtils.convertToJtsGeometry(dto.getPolygon());

        // 创建一个用于存储裁剪后要素的 SimpleFeatureCollection
        //DefaultFeatureCollection clippedCollection = new DefaultFeatureCollection();
        List<Geometry> list = new ArrayList<>();

        // 遍历每个要素
        try (SimpleFeatureIterator iterator = collection.features()) {
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                // 获取要素的几何属性
                Geometry featureGeometry = (Geometry) feature.getDefaultGeometry();
                if (featureGeometry.intersects(clipGeometry)) {                    // 判断要素的几何形状与指定几何形状是否有交集
                    Geometry intersection = featureGeometry.intersection(clipGeometry);
                    if (!intersection.isEmpty()) {
                        // 将交集部分保留下来,作为裁剪后的几何形状
                        //clippedCollection.add(SimpleFeatureBuilder.build(feature.getFeatureType(), new Object[]{intersection}, null));
                        list.add(intersection);
                    }
                }
            }
        }

        return geometryToWKT(list);
    }

筛选分析

 // 筛选分析API接口
    public static final String screeningApi = "{{url}}/geoserver/wfs?service=wfs&version=2.0.0&request=GetFeature&outputFormat=application/json&typeNames={{workspace}}:{{layerName}}";

   public static String screening( String geoserverUrl, String username,String password,String workspace,String layerName, Map<String, Object> filter) {
        try {
            String urlStr = buildUrl(screeningApi, geoserverUrl, workspace, layerName);
            String filterStr = buildCQLFilter(filter);
            urlStr = urlStr + "&" + filterStr;
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            HttpGet httpGet = new HttpGet(urlStr);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return "后台异常";
        }
     }

割裂

    // 割裂API接口
    public static final String splitApi = "{{url}}/geoserver/wfs?service=wfs&version=2.0.0&request=GetFeature&outputFormat=application/json&typeNames={{workspace}}:{{layerName}}&splitField={{splitField}}";
    public static String split(String geoserverUrl, String username,String password,String workspace,String layerName,
            String splitField) {
        try {
            String urlStr = buildUrl(splitApi, geoserverUrl, workspace, layerName, splitField);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            HttpGet httpGet = new HttpGet(urlStr);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return "后台异常";
        }
    }

交集

intersection

并集

union

差集

difference

缓冲区

    public static String buffer(GeoserverAnalysiBufferDTO dto){
        BufferFeatureCollection bf = new BufferFeatureCollection();
        SimpleFeatureCollection featureCollection = getFeature(dto.getGeoserverUrl(),dto.getUsername(),dto.getPassword(),dto.getWorkspace(),dto.getLayerName());
        //featureCollection.getSchema().getDescriptor();
        String[] attributeHeaders = getAttributeHeaders(featureCollection);
        // 打印属性字段头
        for (String header : attributeHeaders) {
            System.out.println(header);
        }
        SimpleFeatureCollection simpleFeatureCollection = bf.execute(featureCollection, dto.getDistance(), dto.getAttribute());
        return Shp2GeojsonUtils.shape2Geojson(simpleFeatureCollection);
    }
    
   private static String[] getAttributeHeaders(SimpleFeatureCollection featureCollection) {
        // 获取第一个要素
        SimpleFeatureIterator iterator = featureCollection.features();
        Feature feature = iterator.next();
        iterator.close();

        // 获取属性字段
        List<String> attributeHeaders = new ArrayList<>();
        for (Property property : feature.getProperties()) {
            String attributeName = property.getName().getLocalPart();
            attributeHeaders.add(attributeName);
        }

        // 将属性字段头转换为字符串数组并返回
        return attributeHeaders.toArray(new String[0]);
    }

擦除

    public static String newErase(GeoserverAnalysisEraseDTO dto) {
        SimpleFeatureCollection collection = GeoServerAnalysisUtils.getFeature(dto.getGeoserverUrl(), dto.getUsername(), dto.getPassword(), dto.getWorkspace(), dto.getLayerName());
        Geometry oldGeo = SpatialAnalysisUtils.convertToJtsGeometry(dto.getPolygon());
        Geometry resultGeo = null;

        try (SimpleFeatureIterator iterator = collection.features()) {
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                Geometry geometry = (Geometry) feature.getDefaultGeometry();
                if (geometry instanceof org.locationtech.jts.geom.Polygon || geometry instanceof org.locationtech.jts.geom.MultiPolygon) {
                    if (geometry.intersects(oldGeo)) {
                        Geometry difference = geometry.difference(oldGeo);
                        if (resultGeo == null) {
                            resultGeo = difference;
                        } else {
                            resultGeo = resultGeo.union(difference);
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        WKTWriter writer = new WKTWriter();
        return  writer.write(resultGeo);
    }

点距离

    /**
     * 两点之间距离计算
     * @Date 2024/4/7 15:19
     **/
    public static double getDistance(double x1, double y1, double x2, double y2) {
        // 84坐标系构造GeodeticCalculator
        GeodeticCalculator geodeticCalculator = new GeodeticCalculator(DefaultGeographicCRS.WGS84);
        // 起点经纬度
        geodeticCalculator.setStartingGeographicPoint(x1, y1);
        // 末点经纬度
        geodeticCalculator.setDestinationGeographicPoint(x2, y2);
        // 计算距离,单位:米
        return geodeticCalculator.getOrthodromicDistance();
    }

近邻分析

    public static GeoServerNeighborVO getNeighbor(GeoServerNeighborDTO dto) {

        GeoServerNeighborVO vo = new GeoServerNeighborVO();
        double miniDist = Double.MAX_VALUE;

        SimpleFeatureCollection collection = GeoServerAnalysisUtils.getFeature(dto.getGeoserverUrl(), dto.getUsername(), dto.getPassword(), dto.getWorkspace(), dto.getLayerName());

        if (collection != null) {
            // 遍历 feature 集合
            try (SimpleFeatureIterator iterator = collection.features()) {
                while (iterator.hasNext()) {
                    SimpleFeature feature = iterator.next();
                    Geometry geometry = (Geometry) feature.getDefaultGeometry();

                    String jzmc = null;

                    // 检查几何类型是否为点
                    if (geometry instanceof org.locationtech.jts.geom.Point) {
                        Coordinate coordinate = geometry.getCoordinate();
                        Point point = new Point(coordinate.getX(), coordinate.getY());
                        // 获取点的坐标
                        double x = point.getX();
                        double y = point.getY();
                        //System.out.println("Point coordinates: (" + x + ", " + y + ")");
                        //计算距离
                        double distance = findShort(dto.getPolygon(), point);
                        if (distance != 0) {
                            if (distance < miniDist) {
                                miniDist = distance;

                                Object jzmcValue = feature.getAttribute("jzmc");
                                if (jzmcValue != null) {
                                    jzmc = (String) jzmcValue;
                                }
                                vo.setPoint(point);
                                vo.setName(jzmc);
                            }
                        }
                    } else {
                        System.out.println("This feature is not a point.");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        vo.setDistance(miniDist * 100);
        System.out.println("近邻分析结果:" + vo.toString());
        return vo;
    }

面邻域

    public static List<String> getSquareNeighbor(GeoServerNeighborDTO dto) {

        SimpleFeatureCollection collection = GeoServerAnalysisUtils.getFeature(dto.getGeoserverUrl(), dto.getUsername(), dto.getPassword(), dto.getWorkspace(), dto.getLayerName());
        Geometry oldGeo = convertToJtsGeometry(dto.getPolygon());

        //GeoServerSquareNeighborVO vo = new GeoServerSquareNeighborVO();
        List<Geometry> list = new ArrayList<>();
        List<String> result = new ArrayList<>();
        if (collection == null) {
            return result ;
        }
        try (SimpleFeatureIterator iterator = collection.features()) {
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                Geometry geometry = (Geometry) feature.getDefaultGeometry();
                if (geometry instanceof org.locationtech.jts.geom.Polygon || geometry instanceof org.locationtech.jts.geom.MultiPolygon) {
                    // org.locationtech.jts.geom.MultiPolygon multiPolygon = (org.locationtech.jts.geom.MultiPolygon) geometry;
                    if (geometry.intersects(oldGeo)) {
                        list.add(geometry);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("相交:" +  geometryToWKT(list));

        return geometryToWKT(list);
    }
org.geotools org.geotools.arcsde org.geotools.arcsde.data org.geotools.arcsde.data.versioning org.geotools.arcsde.data.view org.geotools.arcsde.filter org.geotools.arcsde.gce org.geotools.arcsde.gce.band org.geotools.arcsde.gce.imageio org.geotools.arcs de.gce.producer org.geotools.arcsde.pool org.geotools.axis org.geotools.brewer.color org.geotools.coverage org.geotools.coverage.grid org.geotools.coverage.grid.io org.geotools.coverage.grid.io.imageio org.geotools.coverage.io org.geotools.coverage.processing org.geotools.coverage.processing.operation org.geotools.data org.geotools.data.collection org.geotools.data.crs org.geotools.data.db2 org.geotools.data.db2.filter org.geotools.data.dir org.geotools.data.gml org.geotools.data.gpx org.geotools.data.gpx.temporal org.geotools.data.h2 org.geotools.data.jdbc org.geotools.data.jdbc.attributeio org.geotools.data.jdbc.datasource org.geotools.data.jdbc.fidmapper org.geotools.data.jdbc.referencing org.geotools.data.memory org.geotools.data.mif org.geotools.data.mysql org.geotools.data.oracle org.geotools.data.oracle.attributeio org.geotools.data.oracle.referencing org.geotools.data.oracle.sdo org.geotools.data.ows org.geotools.data.postgis org.geotools.data.postgis.attributeio org.geotools.data.postgis.collection org.geotools.data.postgis.fidmapper org.geotools.data.postgis.referencing org.geotools.data.property org.geotools.data.shapefile org.geotools.data.shapefile.dbf org.geotools.data.shapefile.indexed org.geotools.data.shapefile.indexed.attribute org.geotools.data.shapefile.prj org.geotools.data.shapefile.shp org.geotools.data.shapefile.shp.xml org.geotools.data.store org.geotools.data.tiger org.geotools.data.view org.geotools.data.vpf org.geotools.data.vpf.exc org.geotools.data.vpf.file org.geotools.data.vpf.ifc org.geotools.data.vpf.io org.geotools.data.vpf.readers org.geotools.data.vpf.util org.geotools.data.wfs org.geotools.data.wms org.geotools.data.wms.request org.geotools.data.wms.response org.geotools.data.wms.xml org.geotools.demo org.geotools.demo.data org.geotools.demo.example org.geotools.demo.features org.geotools.demo.geometry org.geotools.demo.introduction org.geotools.demo.jts org.geotools.demo.libraryJTS org.geotools.demo.main org.geotools.demo.mappane org.geotools.demo.metadata.example org.geotools.demo.postgis org.geotools.demo.swing org.geotools.demo.swing.process org.geotools.demo.widgets org.geotools.demo.xml org.geotools.display.canvas org.geotools.display.canvas.map org.geotools.display.event org.geotools.display.geom org.geotools.display.style org.geotools.factory org.geotools.feature org.geotools.feature.collection org.geotools.feature.simple org.geotools.feature.type org.geotools.feature.visitor org.geotools.filter org.geotools.filter.capability org.geotools.filter.expression org.geotools.filter.function org.geotools.filter.function.math org.geotools.filter.identity org.geotools.filter.parser org.geotools.filter.spatial org.geotools.filter.text.cql2 org.geotools.filter.text.txt org.geotools.filter.v1_0 org.geotools.filter.v1_0.capabilities org.geotools.filter.v1_1 org.geotools.filter.v1_1.capabilities org.geotools.filter.visitor org.geotools.gce.arcgrid org.geotools.gce.geotiff org.geotools.gce.geotiff.crs_adapters org.geotools.gce.geotiff.IIOMetadataAdpaters org.geotools.gce.geotiff.IIOMetadataAdpaters.utils org.geotools.gce.geotiff.IIOMetadataAdpaters.utils.codes org.geotools.gce.gtopo30 org.geotools.gce.image org.geotools.gce.imagemosaic org.geotools.gce.imagepyramid org.geotools.geometry org.geotools.geometry.array org.geotools.geometry.coordinatesequence org.geotools.geometry.iso org.geotools.geometry.iso.aggregate org.geotools.geometry.iso.complex org.geotools.geometry.iso.coordinate org.geotools.geometry.iso.index org.geotools.geometry.iso.index.quadtree org.geotools.geometry.iso.io org.geotools.geometry.iso.io.wkt org.geotools.geometry.iso.operation org.geotools.geometry.iso.operation.overlay org.geotools.geometry.iso.operation.relate org.geotools.geometry.iso.primitive org.geotools.geometry.iso.root org.geotools.geometry.iso.topograph2D org.geotools.geometry.iso.topograph2D.index org.geotools.geometry.iso.topograph2D.util org.geotools.geometry.iso.util org.geotools.geometry.iso.util.algorithm2D org.geotools.geometry.iso.util.algorithmND org.geotools.geometry.iso.util.elem2D org.geotools.geometry.iso.util.interpolation org.geotools.geometry.iso.util.topology org.geotools.geometry.jts org.geotools.geometry.jts.coordinatesequence org.geotools.geometry.jts.spatialschema org.geotools.geometry.jts.spatialschema.geometry org.geotools.geometry.jts.spatialschema.geometry.aggregate org.geotools.geometry.jts.spatialschema.geometry.complex org.geotools.geometry.jts.spatialschema.geometry.geometry org.geotools.geometry.jts.spatialschema.geometry.primitive org.geotools.geometry.text org.geotools.gml org.geotools.gml.producer org.geotools.gml2 org.geotools.gml2.bindings org.geotools.gml3 org.geotools.gml3.bindings org.geotools.gml3.bindings.smil org.geotools.gml3.smil org.geotools.gpx org.geotools.gpx.bean org.geotools.gpx.binding org.geotools.graph.build org.geotools.graph.build.basic org.geotools.graph.build.feature org.geotools.graph.build.line org.geotools.graph.build.opt org.geotools.graph.build.polygon org.geotools.graph.io org.geotools.graph.io.standard org.geotools.graph.path org.geotools.graph.structure org.geotools.graph.structure.basic org.geotools.graph.structure.line org.geotools.graph.structure.opt org.geotools.graph.traverse org.geotools.graph.traverse.basic org.geotools.graph.traverse.standard org.geotools.graph.util org.geotools.graph.util.delaunay org.geotools.graph.util.geom org.geotools.graph.util.graph org.geotools.gui.headless org.geotools.gui.swing org.geotools.gui.swing.contexttree org.geotools.gui.swing.contexttree.column org.geotools.gui.swing.contexttree.node org.geotools.gui.swing.contexttree.popup org.geotools.gui.swing.contexttree.renderer org.geotools.gui.swing.crschooser org.geotools.gui.swing.datachooser org.geotools.gui.swing.datachooser.model org.geotools.gui.swing.demo org.geotools.gui.swing.event org.geotools.gui.swing.filter org.geotools.gui.swing.icon org.geotools.gui.swing.image org.geotools.gui.swing.map.map2d org.geotools.gui.swing.map.map2d.control org.geotools.gui.swing.map.map2d.decoration org.geotools.gui.swing.map.map2d.event org.geotools.gui.swing.map.map2d.handler org.geotools.gui.swing.map.map2d.listener org.geotools.gui.swing.map.map2d.strategy org.geotools.gui.swing.misc org.geotools.gui.swing.misc.filter org.geotools.gui.swing.misc.Render org.geotools.gui.swing.process org.geotools.gui.swing.propertyedit org.geotools.gui.swing.propertyedit.filterproperty org.geotools.gui.swing.propertyedit.model org.geotools.gui.swing.propertyedit.styleproperty org.geotools.gui.swing.referencing org.geotools.gui.swing.style org.geotools.gui.swing.style.sld org.geotools.gui.swing.table org.geotools.gui.swing.tree org.geotools.image org.geotools.image.io org.geotools.image.io.metadata org.geotools.image.io.mosaic org.geotools.image.io.netcdf org.geotools.image.io.stream org.geotools.image.io.text org.geotools.image.jai org.geotools.image.palette org.geotools.index org.geotools.index.quadtree org.geotools.index.quadtree.fs org.geotools.index.rtree org.geotools.index.rtree.cachefs org.geotools.index.rtree.database org.geotools.index.rtree.database.mysql org.geotools.index.rtree.fs org.geotools.index.rtree.memory org.geotools.io org.geotools.jdbc org.geotools.kml org.geotools.kml.bindings org.geotools.legend org.geotools.map org.geotools.map.event org.geotools.math org.geotools.measure org.geotools.metadata org.geotools.metadata.iso org.geotools.metadata.iso.citation org.geotools.metadata.iso.constraint org.geotools.metadata.iso.content org.geotools.metadata.iso.distribution org.geotools.metadata.iso.extent org.geotools.metadata.iso.identification org.geotools.metadata.iso.lineage org.geotools.metadata.iso.maintenance org.geotools.metadata.iso.quality org.geotools.metadata.iso.spatial org.geotools.metadata.sql org.geotools.nature org.geotools.openoffice org.geotools.ows org.geotools.ows.bindings org.geotools.ows.v1_1 org.geotools.parameter org.geotools.process org.geotools.process.impl org.geotools.process.literal org.geotools.referencing org.geotools.referencing.crs org.geotools.referencing.cs org.geotools.referencing.datum org.geotools.referencing.example org.geotools.referencing.factory org.geotools.referencing.factory.epsg org.geotools.referencing.factory.wms org.geotools.referencing.operation org.geotools.referencing.operation.builder org.geotools.referencing.operation.matrix org.geotools.referencing.operation.projection org.geotools.referencing.operation.transform org.geotools.referencing.piecewise org.geotools.referencing.wkt org.geotools.renderer org.geotools.renderer.i18n org.geotools.renderer.lite org.geotools.renderer.lite.gridcoverage2d org.geotools.renderer.shape org.geotools.renderer.shape.shapehandler.jts org.geotools.renderer.shape.shapehandler.simple org.geotools.renderer.style org.geotools.repository org.geotools.repository.adaptable org.geotools.repository.defaults org.geotools.repository.postgis org.geotools.repository.property org.geotools.repository.shapefile org.geotools.repository.styling org.geotools.repository.wfs org.geotools.repository.wms org.geotools.sld org.geotools.sld.bindings org.geotools.styling org.geotools.styling.visitor org.geotools.svg org.geotools.test org.geotools.text org.geotools.text.filter org.geotools.util org.geotools.util.logging org.geotools.utils org.geotools.utils.coveragetiler org.geotools.utils.imagemosaic org.geotools.utils.imageoverviews org.geotools.utils.imagepyramid org.geotools.utils.progress org.geotools.validation org.geotools.validation.attributes org.geotools.validation.dto org.geotools.validation.network org.geotools.validation.relate org.geotools.validation.spatial org.geotools.validation.xml org.geotools.wfs org.geotools.wfs.bindings org.geotools.wfs.protocol org.geotools.wfs.v_1_0_0.data org.geotools.wfs.v_1_1_0.data org.geotools.xlink org.geotools.xml org.geotools.xml.filter org.geotools.xml.gml org.geotools.xml.handlers org.geotools.xml.handlers.xsi org.geotools.xml.impl org.geotools.xml.impl.jxpath org.geotools.xml.schema org.geotools.xml.schema.impl org.geotools.xml.styling org.geotools.xml.test org.geotools.xml.transform org.geotools.xml.wfs org.geotools.xml.xLink org.geotools.xml.xsi org.geotools.xs org.geotools.xs.bindings org.geotools.xs.facets
GeoTools 是一个开源的 Java 库,用于处理地理空间数据和地图的创建、分析和渲染。它提供了一系列的工具和 API,可以轻松地读取、写入和转换各种格式的地理数据。以下是使用 GeoTools 进行基本操作的步骤: 1. 导入 GeoTools 库和相关依赖。 ```java import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.feature.FeatureIterator; import org.geotools.geometry.jts.JTSFactoryFinder; import org.opengis.feature.simple.SimpleFeature; import org.opengis.geometry.Geometry; ``` 2. 读取地理数据文件。 ```java File file = new File("path/to/data/file.shp"); FileDataStore store = FileDataStoreFinder.getDataStore(file); SimpleFeatureCollection collection = store.getFeatureSource().getFeatures(); ``` 3. 遍历地理数据集合。 ```java SimpleFeatureIterator iterator = collection.features(); try { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); // do something with the geometry } } finally { iterator.close(); } ``` 4. 创建新的地理数据。 ```java // create a new point GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); Point point = geometryFactory.createPoint(new Coordinate(10.0, 20.0)); // create a new feature SimpleFeatureType featureType = DataUtilities.createType("Location", "geometry:Point,name:String"); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); featureBuilder.add(point); featureBuilder.add("New Location"); SimpleFeature feature = featureBuilder.buildFeature(null); ``` 这些步骤只是 GeoTools 可以完成的操作的一部分。GeoTools 还提供了许多其他的功能,例如地图渲染、地理分析和地理空间数据库的访问。如需了解更多信息,请访问 GeoTools 的官方网站。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值