GeoTools教程

参考网站:
https://blog.csdn.net/oyinhezhiguang/category_10982679.html
https://blog.csdn.net/sipengfei_/article/details/11246386

新建SpringBoot+GeoTools项目

crs包:空间坐标系
datsource包:数据源
feature包:图形要素
filter包:过滤


image.png

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.wzf</groupId>
    <artifactId>geotools</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>geotools</name>
    <description>geotools</description>

    <properties>
        <java.version>1.8</java.version>
        <geotools.version>25.0</geotools.version>
    </properties>

    <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>
        <repository>
            <id>osgeo-snapshot</id>
            <name>OSGeo Snapshot Repository</name>
            <url>https://repo.osgeo.org/repository/snapshot/</url>
            <snapshots><enabled>true</enabled></snapshots>
            <releases><enabled>false</enabled></releases>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

        <!-- geotools -->
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-referencing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-cql</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools.jdbc</groupId>
            <artifactId>gt-jdbc-postgis</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <inherited>true</inherited>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

crs

CrsUtil.java

package com.wzf.geotools.crs;

import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;


// crs实现不同坐标系的坐标转换
public class CrsUtil {

    public void crsTransform() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        // 通常逻辑上理解经度应该是横坐标x,纬度是y,可是这里经度要填到y,纬度x,否则会报错
        Coordinate coordinate = new Coordinate(30, 100);
        Point point = geometryFactory.createPoint(coordinate);

        CoordinateReferenceSystem crs1 = CRS.decode("EPSG:4326");
        CoordinateReferenceSystem crs2 = CRS.decode("EPSG:3857");
        // allow for some error due to different datums
        boolean lenient = true;
        MathTransform transform = CRS.findMathTransform(crs1, crs2, lenient);
        Geometry geometry = JTS.transform(point, transform);
        System.out.println(geometry);
    }


    // 测试
    public static void main(String[] args) throws Exception {
        CrsUtil crsUtil = new CrsUtil();
        crsUtil.crsTransform();
    }
}

datasource

PostgisDatasource.java

package com.wzf.geotools.datasource;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.simple.SimpleFeature;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


// 连接postgis数据源,读取数据
public class PostgisDatasource {

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap();
        // 需要连接何种数据库 postgis
        params.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
        // ip地址
        params.put(PostgisNGDataStoreFactory.HOST.key, "127.0.0.1");
        // 端口号
        params.put(PostgisNGDataStoreFactory.PORT.key, 5432);
        // 需要连接的数据库名
        params.put(PostgisNGDataStoreFactory.DATABASE.key, "sdc");
        // 架构
        params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");
        // 用户名
        params.put(PostgisNGDataStoreFactory.USER.key, "postgres");
        // 密码
        params.put(PostgisNGDataStoreFactory.PASSWD.key, "123456");
        try {
            // 获取存储空间
            DataStore dataStore = DataStoreFinder.getDataStore(params);
            // 根据表名获取source
            SimpleFeatureSource featureSource = dataStore.getFeatureSource("city");
            SimpleFeatureCollection features = featureSource.getFeatures();
            SimpleFeatureIterator iterator = features.features();
            while(iterator.hasNext()){
                SimpleFeature feature = iterator.next();
                // 获取 wkt feature
                Object geometry = feature.getDefaultGeometry();
                System.out.println(geometry.toString());
                // 获取属性列表
                List<Object> attributes = feature.getAttributes();
                System.out.println(attributes.toString());
            }
            iterator.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ShapeDatasource.java

package com.wzf.geotools.datasource;

import com.wzf.geotools.feature.FeatureTypeUtil;
import com.wzf.geotools.feature.FeatureUtil;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureSource;
import org.geotools.data.Transaction;
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.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 操作shape数据源
public class ShapeDatasource {

    // 读取shape文件
    public void readShapeFile(File shapeFile) throws Exception {
        ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shapeFile.toURI().toURL());
        shapefileDataStore.setCharset(Charset.forName("UTF-8"));
        String typeName = shapefileDataStore.getTypeNames()[0];
        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = shapefileDataStore.getFeatureSource(typeName);
        FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures();
        FeatureIterator<SimpleFeature> iterator = collection.features();
        while(iterator.hasNext()){
            SimpleFeature feature = iterator.next();
            List<Object> attributes = feature.getAttributes();
            System.out.println(attributes);
        }
        iterator.close();
    }


    // 写入shape文件
    public void writeShapeFile(File shapeFile) throws Exception {
        // 创建要素
        SimpleFeatureType featureType = FeatureTypeUtil.createPointFeatureTypeByStr();
        FeatureUtil featureUtil = new FeatureUtil();
        List<SimpleFeature> list = featureUtil.createPoint();
        SimpleFeatureCollection collection = new ListFeatureCollection(featureType, list);
        // 构建参数,创建ShapefileDataStore
        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
        Map<String, Serializable> params = new HashMap<>();
        params.put("url", shapeFile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);
        ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        dataStore.createSchema(featureType);
        dataStore.setCharset(Charset.forName("UTF-8"));
        // 写入要素
        Transaction transaction = new DefaultTransaction("create");
        String typeName = dataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            featureStore.setTransaction(transaction);
            featureStore.addFeatures(collection);
            transaction.commit();
        }
    }


    // 测试
    public static void main(String[] args) throws Exception {
        File file = new File("E:\\temp\\temp\\test.shp");
        ShapeDatasource shapeDatasource = new ShapeDatasource();

        shapeDatasource.writeShapeFile(file);

        shapeDatasource.readShapeFile(file);
    }
}

feature

CoordinateSequenceUtil.java

package com.wzf.geotools.feature;

import it.geosolutions.jaiext.jts.CoordinateSequence2D;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.Point;


// 通过CoordinateSequence创建点线面geometry
public class CoordinateSequenceUtil {

    // 通过CoordinateSequence创建点
    public Point createPointByCoordinateSequence(){
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        CoordinateSequence2D coordinateSequence = new CoordinateSequence2D(100,30);
        Point point = geometryFactory.createPoint(coordinateSequence);
        return point;
    }


    // 通过CoordinateSequence创建多点
    public MultiPoint createMultiPointByCoordinateSequence(){
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        CoordinateSequence2D coordinateSequence = new CoordinateSequence2D(100,30,110,35);
        MultiPoint multiPoint = geometryFactory.createMultiPoint(coordinateSequence);
        return multiPoint;
    }


    // 通过CoordinateSequence创建线
    public LineString createLineStringByCoordinateSequence(){
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        CoordinateSequence2D coordinateSequence = new CoordinateSequence2D(100,30,110,35,120,40);
        LineString lineString = geometryFactory.createLineString(coordinateSequence);
        return lineString;
    }
}

CoordinateUtil.java

package com.wzf.geotools.feature;

import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.*;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;

import java.util.ArrayList;
import java.util.List;

// 通过coordinate创建点线面geometry
public class CoordinateUtil {

    // 通过coordinate创建点
    public Point createPointByCoordinete() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate = new Coordinate(100, 30);
        Point point = geometryFactory.createPoint(coordinate);
        return point;
    }


    // 通过coordinate创建多点
    public MultiPoint createMultiPointByCoordinete() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate1 = new Coordinate(100, 30);
        Coordinate coordinate2 = new Coordinate(110, 30);
        Coordinate coordinate3 = new Coordinate(120, 30);
        Coordinate[] coordinates = new Coordinate[]{coordinate1, coordinate2, coordinate3};
        MultiPoint point = geometryFactory.createMultiPoint(coordinates);
        return point;
    }


    // 通过coordinate创建线
    public LineString createLineStringByCoordinete() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate1 = new Coordinate(100, 30);
        Coordinate coordinate2 = new Coordinate(110, 30);
        Coordinate coordinate3 = new Coordinate(120, 30);
        Coordinate[] coordinates = new Coordinate[]{coordinate1, coordinate2, coordinate3};
        LineString lineString = geometryFactory.createLineString(coordinates);
        return lineString;
    }


    // 通过coordinate创建多线
    public MultiLineString createMultiLineStringByCoordinete() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate1 = new Coordinate(100, 30);
        Coordinate coordinate2 = new Coordinate(110, 30);
        Coordinate coordinate3 = new Coordinate(120, 30);
        Coordinate[] coordinates = new Coordinate[]{coordinate1, coordinate2, coordinate3};

        LineString lineString = geometryFactory.createLineString(coordinates);
        Coordinate coordinate4 = new Coordinate(110, 40);
        Coordinate coordinate5 = new Coordinate(120, 40);
        Coordinate[] coordinates2 = new Coordinate[]{coordinate4, coordinate5};

        LineString lineString2 = geometryFactory.createLineString(coordinates2);
        LineString[] lineStrings = new LineString[]{lineString, lineString2};
        MultiLineString multiLineString = geometryFactory.createMultiLineString(lineStrings);
        return multiLineString;
    }


    // 通过coordinate创建面
    public Polygon createPolygonByCoordinate() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate1 = new Coordinate(100, 30);
        Coordinate coordinate2 = new Coordinate(110, 30);
        Coordinate coordinate3 = new Coordinate(105, 35);
        Coordinate[] coordinates = new Coordinate[]{coordinate1, coordinate2, coordinate3, coordinate1};
        LinearRing linearRing = geometryFactory.createLinearRing(coordinates);
        LinearRing holes[] = null;
        Polygon polygon = geometryFactory.createPolygon(linearRing, holes);
        return polygon;
    }


    // 通过coordinate创建圆
    public Polygon createCircleByCoordinate() throws Exception {
//        GeometryBuilder builder = new GeometryBuilder();
//        // 经度,纬度,半径(经纬度),边的数量
//        Polygon circle = builder.circle(110, 30, 10, 32);
        // 计算转换坐标系的转换矩阵
        CoordinateReferenceSystem crs1 = CRS.decode("EPSG:4326");
        CoordinateReferenceSystem crs2 = CRS.decode("EPSG:3857");
        MathTransform transform = CRS.findMathTransform(crs1, crs2, true);
        MathTransform transform2 = CRS.findMathTransform(crs2, crs1, true);
        // 转换中心点
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate center = new Coordinate(30, 100);
        Point point = geometryFactory.createPoint(center);
        Point point2 = (Point) JTS.transform(point, transform);
        // 计算缓冲区(缓冲区半径10km)
        Polygon buffer3857 = (Polygon) point2.buffer(10);
        // 转换缓冲区
        Polygon buffer4326 = (Polygon) JTS.transform(buffer3857, transform2);
        // 调整缓冲区的经纬度顺序
        Coordinate[] coordinates = buffer4326.getCoordinates();
        List<Coordinate> coords = new ArrayList<>();
        for (int i = 0; i < coordinates.length; i++) {
            coords.add(new Coordinate(coordinates[i].y, coordinates[i].x));
        }
        LinearRing linearRing = geometryFactory.createLinearRing(coords.toArray(new Coordinate[]{}));
        Polygon polygon = geometryFactory.createPolygon(linearRing, null);
        return polygon;
    }


    // 测试
    public static void main(String[] args) throws Exception {
        CoordinateUtil coordinateUtil = new CoordinateUtil();

        Point point = coordinateUtil.createPointByCoordinete();
        System.out.println(point);

        MultiPoint multiPoint = coordinateUtil.createMultiPointByCoordinete();
        System.out.println(multiPoint);

        LineString lineString = coordinateUtil.createLineStringByCoordinete();
        System.out.println(lineString);

        MultiLineString multiLineString = coordinateUtil.createMultiLineStringByCoordinete();
        System.out.println(multiLineString);

        Polygon polygon = coordinateUtil.createPolygonByCoordinate();
        System.out.println(polygon);

        Polygon circle = coordinateUtil.createCircleByCoordinate();
        System.out.println(circle);
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate center = new Coordinate(100.05, 30);
        Point point0 = geometryFactory.createPoint(center);
        System.out.println(circle.contains(point0));
    }
}

FeatureTypeUtil.java

package com.wzf.geotools.feature;

import org.geotools.data.DataUtilities;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;


// 创建要素类型
public class FeatureTypeUtil {

    // 通过字符串创建 点要素类型
    public static SimpleFeatureType createPointFeatureTypeByStr() throws SchemaException {
        String typeStr = "the_geom:Point:srid=4326,name:String,number:Integer";
        return DataUtilities.createType("typeName", typeStr);
    }

    // 通过字符串创建 线要素类型
    public static SimpleFeatureType createLineStringFeatureTypeByStr() throws SchemaException {
        String typeStr = "the_geom:LineString:srid=4326,name:String,number:Integer";
        return DataUtilities.createType("typeName", typeStr);
    }

    // 通过字符串创建 面要素类型
    public static SimpleFeatureType createPolygonFeatureTypeByStr() throws SchemaException {
        String typeStr = "the_geom:Polygon:srid=4326,name:String,number:Integer";
        return DataUtilities.createType("typeName", typeStr);
    }


    // 通过SimpleFeatureTypeBuilder创建 点要素类型
    public static SimpleFeatureType createPointFeatureTypeByBuilder() throws FactoryException {
        CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("typeName2");
        builder.setCRS(crs);
        builder.add("the_geom", Point.class);
        builder.length(15).add("name", String.class);
        builder.add("number", Integer.class);
        return builder.buildFeatureType();
    }

    // 通过SimpleFeatureTypeBuilder创建 线要素类型
    public static SimpleFeatureType createLineStringFeatureTypeByBuilder() throws FactoryException {
        CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("typeName2");
        builder.setCRS(crs);
        builder.add("the_geom", LineString.class);
        builder.length(15).add("name", String.class);
        builder.add("number", Integer.class);
        return builder.buildFeatureType();
    }

    // 通过SimpleFeatureTypeBuilder创建 面要素类型
    public static SimpleFeatureType createPolygonFeatureTypeByBuilder() throws FactoryException {
        CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("typeName2");
        builder.setCRS(crs);
        builder.add("the_geom", Polygon.class);
        builder.length(15).add("name", String.class);
        builder.add("number", Integer.class);
        return builder.buildFeatureType();
    }


    // 测试
    public static void main(String[] args) throws Exception {
        SimpleFeatureType featureType1 = FeatureTypeUtil.createPointFeatureTypeByStr();
        System.out.println(featureType1);
        SimpleFeatureType featureType2 = FeatureTypeUtil.createLineStringFeatureTypeByStr();
        System.out.println(featureType2);
        SimpleFeatureType featureType3 = FeatureTypeUtil.createPolygonFeatureTypeByStr();
        System.out.println(featureType3);

        SimpleFeatureType featureType11 = FeatureTypeUtil.createPointFeatureTypeByBuilder();
        System.out.println(featureType11);
        SimpleFeatureType featureType22 = FeatureTypeUtil.createLineStringFeatureTypeByBuilder();
        System.out.println(featureType22);
        SimpleFeatureType featureType33 = FeatureTypeUtil.createPolygonFeatureTypeByBuilder();
        System.out.println(featureType33);
    }
}

FeatureUtil.java

package com.wzf.geotools.feature;

import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.util.ArrayList;
import java.util.List;

// 创建点线面要素
public class FeatureUtil {

    // 创建点
    public List<SimpleFeature> createPoint() throws Exception {
        List<SimpleFeature> list = new ArrayList();

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        SimpleFeatureType featureType = FeatureTypeUtil.createPointFeatureTypeByStr();
//        SimpleFeatureType featureType = FeatureTypeUtil.createPointFeatureTypeByBuilder();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
        for (int i = 0; i < 10; i++) {
            // 创建geometry
            Coordinate coordinate = new Coordinate(100+i, 30+i);
            Point point = geometryFactory.createPoint(coordinate);
            // 创建feature
            featureBuilder.set("the_geom", point);
            featureBuilder.set("name", "名称-"+i);
            featureBuilder.set("number", i);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            list.add(feature);
        }
        return list;
    }


    // 创建线
    public SimpleFeature createLine() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        SimpleFeatureType featureType = FeatureTypeUtil.createLineStringFeatureTypeByStr();
//        SimpleFeatureType featureType = FeatureTypeUtil.createLineStringFeatureTypeByBuilder();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);

        // 构建线geometry
        List<Coordinate> coordList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Coordinate coordinate = new Coordinate(100+i, 30+i);
            coordList.add(coordinate);
        }
        Coordinate[] array = coordList.toArray(new Coordinate[]{});
        LineString lineString = geometryFactory.createLineString(array);

        // 创建feature
        featureBuilder.set("the_geom", lineString);
        featureBuilder.set("name", "名称");
        featureBuilder.set("number", 10);
        SimpleFeature feature = featureBuilder.buildFeature(null);
        return feature;
    }


    // 测试
    public static void main(String[] args) throws Exception {
        FeatureUtil featureUtil = new FeatureUtil();

        List<SimpleFeature> list = featureUtil.createPoint();
        for (SimpleFeature simpleFeature: list) {
            List<Object> attributes = simpleFeature.getAttributes();
            System.out.println(attributes);
        }

        SimpleFeature line = featureUtil.createLine();
        List<Object> attributes = line.getAttributes();
        System.out.println(attributes);
    }
}

WktUtil.java

package com.wzf.geotools.feature;

import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.WKTReader;


// 通过wkt创建点线面geometry
public class WktUtil {

    // 通过wkt创建点
    public Point createPointByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        Point point = (Point)wktReader.read("POINT(100 30)");
        return point;
    }


    // 通过wkt创建多点
    public MultiPoint createMultiPointByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        MultiPoint point = (MultiPoint)wktReader.read("MULTIPOINT(100 30)");
        return point;
    }


    // 通过wkt创建线
    public LineString createLineStringByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        LineString lineString = (LineString)wktReader.read("LINESTRING(100 30, 110 35, 120 40)");
        return lineString;
    }


    // 通过wkt创建多线
    public MultiLineString createMultiLineStringByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        MultiLineString multiLineString = (MultiLineString)wktReader.read("MULTILINESTRING((100 30, 110 35),(120 40, 125 40))");
        return multiLineString;
    }


    // 通过wkt创建面
    public Polygon createPolygonByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        // 里面的小括号个数可以有多个,第一个被后面的那些挖洞
//        Polygon polygon = (Polygon)wktReader.read("POLYGON((100 30,115 35,113 35))");
        Polygon polygon = (Polygon)wktReader.read("POLYGON((100 30,115 35,113 35, 100 30),(111 30, 112 30, 112 32, 111 30))");
        return polygon;
    }


    // 测试
    public static void main(String[] args) throws Exception {
        WktUtil wktUtil = new WktUtil();

        Point point = wktUtil.createPointByWkt();
        System.out.println(point);

        MultiPoint multiPoint = wktUtil.createMultiPointByWkt();
        System.out.println(multiPoint);

        LineString lineString = wktUtil.createLineStringByWkt();
        System.out.println(lineString);

        MultiLineString multiLineString = wktUtil.createMultiLineStringByWkt();
        System.out.println(multiLineString);

        Polygon polygon = wktUtil.createPolygonByWkt();
        System.out.println(polygon);
    }
}

filter

CqlFilter.java

package com.wzf.geotools.filter;

import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;

// https://blog.csdn.net/sipengfei_/article/details/112463864
public class CqlFilter {

    public void cqlFilter() throws Exception {
        // 单条件过滤
        Filter filter = CQL.toFilter("number >= 10");
        // 多条件过滤
        List<Filter> filters = CQL.toFilterList("name = 'test'; number>10");
        // between过滤
        Filter filter1 = CQL.toFilter("number between 10 and 20");
        // 几何关系过滤
//        Filter result = CQL.toFilter("CONTAINS(ATTR1, POINT(1 2))" );
//        Filter result = CQL.toFilter("BBOX(ATTR1, 10,20,30,40)" );
//        Filter result = CQL.toFilter("DWITHIN(ATTR1, POINT(1 2), 10, kilometers)" );
//        Filter result = CQL.toFilter("CROSS(ATTR1, LINESTRING(1 2, 10 15))" );
//        Filter result = CQL.toFilter("INTERSECT(ATTR1, GEOMETRYCOLLECTION (POINT (10 10),POINT (30 30),LINESTRING (15 15, 20 20)) )" );
//        Filter result = CQL.toFilter("CROSSES(ATTR1, LINESTRING(1 2, 10 15))" );
//        Filter result = CQL.toFilter("INTERSECTS(ATTR1, GEOMETRYCOLLECTION (POINT (10 10),POINT (30 30),LINESTRING (15 15, 20 20)) )" );
    }


    // 测试几何关系:shape文件中的图形与自定义图形之间的空间几何关系
    public static void main(String[] args) throws Exception {
        // 属性过滤
//        Filter filter = CQL.toFilter("name='名称-6' and number>5");

        // 矩形范围bbox过滤
//        Filter filter = CQL.toFilter("BBOX(the_geom, 103,30,105,35)");

        // 圆形范围过滤
//        CoordinateUtil coordinateUtil = new CoordinateUtil();
//        Polygon circle = coordinateUtil.createCircleByCoordinate();
//        Filter filter = CQL.toFilter("INTERSECTS(the_geom, "+circle+")" );

        // 多边形范围过滤
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate1 = new Coordinate(100, 30);
        Coordinate coordinate2 = new Coordinate(105, 30);
        Coordinate coordinate3 = new Coordinate(103, 35);
        Coordinate[] coordinates = new Coordinate[]{coordinate1, coordinate2, coordinate3, coordinate1};
        LinearRing linearRing = geometryFactory.createLinearRing(coordinates);
        LinearRing holes[] = null;
        Polygon polygon = geometryFactory.createPolygon(linearRing, holes);
        Filter filter = CQL.toFilter("INTERSECTS(the_geom, "+polygon+")" );

        File shapeFile = new File("E:\\temp\\temp\\test.shp");
        ShapefileDataStore dataStore = new ShapefileDataStore(shapeFile.toURI().toURL());
        dataStore.setCharset(Charset.forName("UTF-8"));
        String type = dataStore.getTypeNames()[0];
        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(type);
        FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures(filter);
        FeatureIterator<SimpleFeature> iterator = collection.features();
        while(iterator.hasNext()){
            SimpleFeature feature = iterator.next();
            List<Object> attributes = feature.getAttributes();
            System.out.println(attributes);
        }
        iterator.close();
    }
}

swing

Map.java

package com.wzf.geotools.swing;

import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;

import java.io.File;

public class Map {
    public static void main(String[] args) throws Exception {
        // 选择一个shp文件
        File file = JFileDataStoreChooser.showOpenFile("shp", null);
        if (file == null) {
            return;
        }

        //加载shp图层数据源
        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = store.getFeatureSource();

        // 创建一个地图容器
        MapContent map = new MapContent();
        map.setTitle("Quickstart");

        //创建一个简单的样式,并将样式和shp数据源加载到一个图层上
        Style style = SLD.createSimpleStyle(featureSource.getSchema());
        Layer layer = new FeatureLayer(featureSource, style);

        //在地图容器添加图层
        map.addLayer(layer);

        // 展示地图
        JMapFrame.showMap(map);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容