GeoTools教程

參考網(wǎng)站:
https://blog.csdn.net/oyinhezhiguang/category_10982679.html
https://blog.csdn.net/sipengfei_/article/details/11246386

新建SpringBoot+GeoTools項目

crs包:空間坐標系
datsource包:數(shù)據(jù)源
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實現(xiàn)不同坐標系的坐標轉(zhuǎn)換
public class CrsUtil {

    public void crsTransform() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        // 通常邏輯上理解經(jīng)度應(yīng)該是橫坐標x,緯度是y,可是這里經(jīng)度要填到y(tǒng),緯度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數(shù)據(jù)源,讀取數(shù)據(jù)
public class PostgisDatasource {

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap();
        // 需要連接何種數(shù)據(jù)庫 postgis
        params.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
        // ip地址
        params.put(PostgisNGDataStoreFactory.HOST.key, "127.0.0.1");
        // 端口號
        params.put(PostgisNGDataStoreFactory.PORT.key, 5432);
        // 需要連接的數(shù)據(jù)庫名
        params.put(PostgisNGDataStoreFactory.DATABASE.key, "sdc");
        // 架構(gòu)
        params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");
        // 用戶名
        params.put(PostgisNGDataStoreFactory.USER.key, "postgres");
        // 密碼
        params.put(PostgisNGDataStoreFactory.PASSWD.key, "123456");
        try {
            // 獲取存儲空間
            DataStore dataStore = DataStoreFinder.getDataStore(params);
            // 根據(jù)表名獲取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數(shù)據(jù)源
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 {
        // 創(chuàng)建要素
        SimpleFeatureType featureType = FeatureTypeUtil.createPointFeatureTypeByStr();
        FeatureUtil featureUtil = new FeatureUtil();
        List<SimpleFeature> list = featureUtil.createPoint();
        SimpleFeatureCollection collection = new ListFeatureCollection(featureType, list);
        // 構(gòu)建參數(shù),創(chuàng)建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創(chuàng)建點線面geometry
public class CoordinateSequenceUtil {

    // 通過CoordinateSequence創(chuàng)建點
    public Point createPointByCoordinateSequence(){
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        CoordinateSequence2D coordinateSequence = new CoordinateSequence2D(100,30);
        Point point = geometryFactory.createPoint(coordinateSequence);
        return point;
    }


    // 通過CoordinateSequence創(chuàng)建多點
    public MultiPoint createMultiPointByCoordinateSequence(){
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        CoordinateSequence2D coordinateSequence = new CoordinateSequence2D(100,30,110,35);
        MultiPoint multiPoint = geometryFactory.createMultiPoint(coordinateSequence);
        return multiPoint;
    }


    // 通過CoordinateSequence創(chuàng)建線
    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創(chuàng)建點線面geometry
public class CoordinateUtil {

    // 通過coordinate創(chuàng)建點
    public Point createPointByCoordinete() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate coordinate = new Coordinate(100, 30);
        Point point = geometryFactory.createPoint(coordinate);
        return point;
    }


    // 通過coordinate創(chuàng)建多點
    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創(chuàng)建線
    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創(chuàng)建多線
    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創(chuàng)建面
    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創(chuàng)建圓
    public Polygon createCircleByCoordinate() throws Exception {
//        GeometryBuilder builder = new GeometryBuilder();
//        // 經(jīng)度,緯度,半徑(經(jīng)緯度),邊的數(shù)量
//        Polygon circle = builder.circle(110, 30, 10, 32);
        // 計算轉(zhuǎn)換坐標系的轉(zhuǎn)換矩陣
        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);
        // 轉(zhuǎn)換中心點
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Coordinate center = new Coordinate(30, 100);
        Point point = geometryFactory.createPoint(center);
        Point point2 = (Point) JTS.transform(point, transform);
        // 計算緩沖區(qū)(緩沖區(qū)半徑10km)
        Polygon buffer3857 = (Polygon) point2.buffer(10);
        // 轉(zhuǎn)換緩沖區(qū)
        Polygon buffer4326 = (Polygon) JTS.transform(buffer3857, transform2);
        // 調(diào)整緩沖區(qū)的經(jīng)緯度順序
        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;


// 創(chuàng)建要素類型
public class FeatureTypeUtil {

    // 通過字符串創(chuàng)建 點要素類型
    public static SimpleFeatureType createPointFeatureTypeByStr() throws SchemaException {
        String typeStr = "the_geom:Point:srid=4326,name:String,number:Integer";
        return DataUtilities.createType("typeName", typeStr);
    }

    // 通過字符串創(chuàng)建 線要素類型
    public static SimpleFeatureType createLineStringFeatureTypeByStr() throws SchemaException {
        String typeStr = "the_geom:LineString:srid=4326,name:String,number:Integer";
        return DataUtilities.createType("typeName", typeStr);
    }

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


    // 通過SimpleFeatureTypeBuilder創(chuàng)建 點要素類型
    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創(chuàng)建 線要素類型
    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創(chuàng)建 面要素類型
    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;

// 創(chuàng)建點線面要素
public class FeatureUtil {

    // 創(chuàng)建點
    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++) {
            // 創(chuàng)建geometry
            Coordinate coordinate = new Coordinate(100+i, 30+i);
            Point point = geometryFactory.createPoint(coordinate);
            // 創(chuàng)建feature
            featureBuilder.set("the_geom", point);
            featureBuilder.set("name", "名稱-"+i);
            featureBuilder.set("number", i);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            list.add(feature);
        }
        return list;
    }


    // 創(chuàng)建線
    public SimpleFeature createLine() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

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

        // 構(gòu)建線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);

        // 創(chuàng)建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創(chuàng)建點線面geometry
public class WktUtil {

    // 通過wkt創(chuàng)建點
    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創(chuàng)建多點
    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創(chuàng)建線
    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創(chuàng)建多線
    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創(chuàng)建面
    public Polygon createPolygonByWkt() throws Exception {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader wktReader = new WKTReader(geometryFactory);
        // 里面的小括號個數(shù)可以有多個,第一個被后面的那些挖洞
//        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");
        // 幾何關(guān)系過濾
//        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)) )" );
    }


    // 測試幾何關(guān)系:shape文件中的圖形與自定義圖形之間的空間幾何關(guān)系
    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圖層數(shù)據(jù)源
        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = store.getFeatureSource();

        // 創(chuàng)建一個地圖容器
        MapContent map = new MapContent();
        map.setTitle("Quickstart");

        //創(chuàng)建一個簡單的樣式,并將樣式和shp數(shù)據(jù)源加載到一個圖層上
        Style style = SLD.createSimpleStyle(featureSource.getSchema());
        Layer layer = new FeatureLayer(featureSource, style);

        //在地圖容器添加圖層
        map.addLayer(layer);

        // 展示地圖
        JMapFrame.showMap(map);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容