GeoTools教程

作者: WebGiser | 来源:发表于2022-04-17 18:55 被阅读0次

参考网站:
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);
    }
}

相关文章

网友评论

    本文标题:GeoTools教程

    本文链接:https://www.haomeiwen.com/subject/wjmlertx.html