GeoTools-地理数据操作Java库

GeoTools是一个开源的Java库,专注于地理空间数据的处理,遵循OGC规范。它利用JTS库支持空间几何,并提供数据格式转换、要素创建及管理等功能。文章介绍了如何通过Maven引入GeoTools,创建空间要素以及使用DataUtilities工具类进行数据操作。

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

GeoTools 是一个开源Java库,为地理空间数据的操作提供了方法,其数据结构基于开放地理空间联盟(OGC)规范

GeoTools结构

  • OpenGIS:地理空间支持
  • JTS(Java Topology Suite):空间几何支持

相关解释

数据格式

  1. WKT(Well-known Text):OGC制定的文本标记语言,用于表示适量几何对象、空间参考系统以及空间参照系统之间的转换。如"POINT(2 2)"表示位于坐标(2,2)的点
  2. WKB(Well-known binary):WKT的二进制表示形式,便于传输和数据库存储
  3. GeoJSON:JSON格式的Feature表达格式。

数据模型

  1. Coordinate:坐标,使用长度为N的数字序列表示N维空间的某个位置,其表达的是空间中的哪个位置
  2. Geometry:空间几何,一般有点Point、线LineString、面Polygon、点集MultiPoint、线集MultiLineString、面集MultiPolygon,其表达的是在空间中哪里绘制什么样的图形
  3. FeatureType:要素类型,是对空间要素的定义,其表达的是这一类的要素包含哪些空间信息和非空间信息。
  4. Feature:空间要素,包含空间信息与非空间信息,其表达的是在地图上绘制的东西以及含义
  5. FeatureCollection:要素集合,包含一系列的空间要素,同时还包括CRS等信息,其表达的是一组具体的空间要素。

GeoUtil的主要流程

使用

Maven引入

<!-- 1. 引入仓库 -->
<repositories>
    <repository>
        <id>osgeo</id>
        <name>OSGeo Release Repository</name>
        <url>https://repo.osgeo.org/repository/release/</url>
        <snapshots><enabled>false</enabled></snapshots>
        <releases><enabled>true</enabled></releases>
    </repository>
</repositories>

<!-- 2. 导入依赖 -->
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.geotools/gt-geojson -->
    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-geojson</artifactId>
        <version>${geotools.version}</version>
    </dependency>
</dependencies>

gt-geojson已包含gt-main等包

自定义简单工具类

简单数据类型或格式间的转换,如点、线、GeoJson、WKT等

@Slf4j
public class GeoUtils {

    /**
     * 地理数据类型
     * 点、线、面、几何集合
     */
    private static final String[] GEO_TYPE = new String[]{"Geometry", "Point", "LineString", "Polygon", "MultiPoint", "MultiLineString", "MultiPolygon", "GeometryCollection"};

    private final static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

    // WKT 读取器
    private final static WKTReader reader = new WKTReader(geometryFactory);
    // GeoJSON 转换器
    private final static GeometryJSON geometryJson = new GeometryJSON(2); // 精度2位小数
    private final static FeatureJSON featureJson = new FeatureJSON(geometryJson);

    /**
     * 获取几何类型
     * @param wkt WKT格式字符串
     * @return 几何类型
     */
    public static String getGeoTypeFromWKT(String wkt){
        String type = null;
        if (Strings.isNotEmpty(wkt)) {
            try {
                Geometry read = reader.read(wkt);
                type = read.getGeometryType();
            }catch (Exception e) {
                log.error("invalid WKT String:", e);
                e.printStackTrace();
            }
        }
        return type;
    }

    /**
     * 点坐标值转换为WKT格式
     * @param x x坐标值
     * @param y y坐标值
     * @return 点类型WKT
     */
    public static String Point2WKT(int x, int y){
        return "POINT(" + x + " " + y + ")";
    }

    /**
     * 线坐标值转换为WKT格式
     * @param x1 起点x坐标值
     * @param y1 起点y坐标值
     * @param x2 终点x坐标值
     * @param y2 终点y坐标值
     * @return 线类型WKT
     */
    public static String Line2WKT(int x1, int y1, int x2, int y2){
        return "LINESTRING("+x1+ " "+y1 + ","+x2+" "+y2 +")";
    }

    /**
     * WKT格式文本对象转换为GeoJSON
     * @param wkt WKT格式文本
     * @return GeoJson对象
     */
    public static String wktToJson(String wkt) {
        String json = null;
        try {
            Geometry geometry = reader.read(wkt);
            json = geometryJson.toString(geometry);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * Geometry对象转换为GeoJSON
     * @param geometry 空间几何对象
     * @return GeoJSON对象
     */
    public static String geoToJson(Geometry geometry) {
        return geometryJson.toString(geometry);
    }

    /**
     * Feature转换为GeoJSON
     * @param feature Feature要素对象
     * @return GeoJSON对象
     */
    public static String featureToJson(SimpleFeature feature){
        String json = null;
        try{
            json = featureJson.toString(feature);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * Feature集合转换为GeoJSON
     * @param features FeatureCollection对象
     * @return GeoJSON文本
     */
    public static String featureCollectionToJson(SimpleFeatureCollection features){
        String json = null;
        try{
            json = featureJson.toString(features);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * 1*2二维坐标数组转换为点对象
     * point(Array) -> coordinate -> Point(Geometry)
     * @param x x坐标
     * @param y y坐标         
     * @return Point(Geometry) 点对象
     */
    public static Point createPoint(double x, double y) {
        return geometryFactory.createPoint(new Coordinate(x, y));
    }


    /**
     * n*2二维坐标数组转换为点集对象
     * points(Array[Array]) -> Point[] -> MultiPoint(Geometry)
     * @param pointArrays n*2数组
     * @return MultiPoint(Geometry) 点集对象
     */
    public static MultiPoint createMultiPoint(double[][] pointArrays){
        int size = pointArrays.length;
        Point[] points = new Point[size];
        for (int i = 0; i < size; i++) {
                points[i] = createPoint(pointArrays[i][0], pointArrays[i][1]);
        }
        return geometryFactory.createMultiPoint(points);
    }
}

要素创建(Builder方式)

builder可使用reset进行复用

空间要素类型
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();

//set the name
typeBuilder.setName( "Flag" );  // type 字段

//add some properties
typeBuilder.add( "name", String.class );
typeBuilder.add( "classification", Integer.class );
typeBuilder.add( "height", Double.class );

//add a geometry property
typeBuilder.setCRS( DefaultGeographicCRS.WGS84 );
typeBuilder.add( "location", Point.class );

//build the type
SimpleFeatureType featureType = typeBuilder.buildFeatureType();
空间要素
//create the builder
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);

//add the values
builder.add( "Canada" );
builder.add( 1 );
builder.add( 20.5 );
builder.add( geometryFactory.createPoint(new Coordinate(-124, 52)) );

//build the feature with provided ID
SimpleFeature feature = builder.buildFeature( "fid.1" );

空间要素集合

List<SimpleFeature> featureList = new ArrayList<>();
features.add(feature);
// 1. 使用FeatureCollection的子类(共用数据源)
SimpleFeatureCollection collection = new ListFeatureCollection(featureType, featureList);

// 2. 使用DataUtilities(静态,复制数据源)
SimpleFeatureCollection collection1 = DataUtilities.collection(featureList);

DataUtilities.collection()方法创建的是DefaultFeatureCollection,其内部是将传入的List<SimpleFeature>另存为Map,所以修改List不会改变该集合;

new ListFeatureCollection 以List格式保存传入的List<SimpleFeature>,本质上是共用同一个List,所以修改List的同时也会改变该集合。

此外,对于ListFeatureCollection,会按照传入的featureType判断Feature格式,不可以存在混合Type。如ListFeatureCollection构造方法会自动修改,而DataUtilities方法会提示警告: Feature Collection contains a heterogeneous mix of features

官方工具类DataUtilities

本质上就是使用约定的文本格式解析内容

createType
public static SimpleFeatureType createType(String typeName,
                                           String typeSpec)
                                    throws SchemaException
public static SimpleFeatureType createType(String namespace,
                                           String name,
                                           String typeSpec)
                                    throws SchemaException

以约定格式的字符串创建FeatureType

格式为:属性名1:属性类型1,属性名2:属性类型2,属性名3:属性类型3,...

其中属性类型可以为以下内容:

  • 0, Integer, int : 表示Integer类型
  • 0.0, Double, double:表示Double类型
  • "", String, string:表示字符串类型
  • Geometry, Point, LineString, … :表示空间对象
  • UUID
  • Date
  • 具体的类对象路径,如java.sql.Timestamp

对于地理空间信息可以以属性名1:属性类型1:提示1进行表示,其中提示的内容为nilllablesrid=<#>

举几个栗子🌰

  1. name:"",age:0,geom:Geometry,centroid:Point,url:java.io.URL"
  2. id:String,polygonProperty:Polygon:srid=32615
  3. identifier:UUID,location:Point,*area:MultiPolygon,created:Date
  4. uuid:UUID,name:String,description:String,time:java.sql.Timestamp
encodeType
public static String encodeType(SimpleFeatureType featureType)

将featureType解释为原typeSpec格式的字符串(属性名1:属性类型1:提示1,...格式)

createFeature
public static SimpleFeature createFeature(SimpleFeatureType featureType,
                                          String line)

以约定格式创建的与featureType定义的属性想对应的字符串要素ID=属性值1|属性值2|属性值3...进行创建

  • 未配置要素ID会随机生成
  • 属性间以|分割
  • 几何数据会使用 WKTReader进行处理,即传入参数以WKT格式表示
  • 注意空格、换行、\等可以采用转义字符\
encodeFeature
public static String encodeFeature(SimpleFeature feature)

将Feature解释为约定格式要素ID=属性值1|属性值2|属性值3...

参考

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值