GeoTools相关 java发布geoserver服务

GeoTools相关

GeoTools–创建shape要素

描述语法应用场景
二维点要素POINT(6 10)学校、基础设施位置
二维多点要素MULTIPOINT(3.5 5.6, 4.8 10.5)
带有线型参照二维点POINT M (1 1 80)气象点
带有线型参照三维点POINT ZM (1 1 5 60)高程点
二维线要素LINESTRING(3 4,10 50,20 25)河流、道路
二维多线要素MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))岛屿的线状行政界线
二维面状要素POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2))面状行政界线
二维多面要素MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3)))岛屿的面状行政界线
要素集合GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))
空点要素POINT EMPTY
空面要素MULTIPOLYGON EMPTY

添加Maven依赖:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <geotools.version>20.5</geotools.version>
        <!--jts版本跟geotools相匹配,20.x后的需要1.16版本-->
        <jts.version>1.16.1</jts.version>
    </properties>        
<!-- geotools start -->
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</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-api</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-metadata</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geometry</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-coverage</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-cql</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-data</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-wkt</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-jdbc</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-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.locationtech.jts</groupId>
            <artifactId>jts-core</artifactId>
            <version>1.16.1</version>
        </dependency>
<!-- geotools end -->
<!--  有的依赖下载不下来需要加入下面配置 -->
<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>

创建点,线,面要素

//通过坐标对象Coordinate创建

//这里注意版本20.x之后的引入包import com.vividsolutions.jts.geom.GeometryFactory;会报错
//应该引入import org.locationtech.jts.geom.GeometryFactory;
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

//创建点要素
Coordinate coord = new Coordinate(1, 1);
Point point = geometryFactory.createPoint(coord);
//创建线要素
Coordinate[] coords = new Coordinate[] {new Coordinate(0, 2), new Coordinate(2, 0), new Coordinate(8, 6) };
LineString line = geometryFactory.createLineString(coordinates);

//创建面要素
Coordinate[] coords  =  new Coordinate[] {new Coordinate(4, 0), new Coordinate(2, 2),     new Coordinate(4, 4), new Coordinate(6, 2), new Coordinate(4, 0) };
LinearRing ring = geometryFactory.createLinearRing( coords );
LinearRing holes[] = null; Polygon polygon = geometryFactory.createPolygon(ring, holes );
//通过WKT创建
//点要素
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
WKTReader reader = new WKTReader(geometryFactory);
Point point = (Point) reader.read("POINT (1 1)");
//线要素
WKTReader reader = new WKTReader( geometryFactory );
LineString line = (LineString) reader.read("LINESTRING(0 2, 2 0, 8 6)");
//面要素
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
WKTReader reader = new WKTReader( geometryFactory );
Polygon polygon = (Polygon) reader.read("POLYGON((20 10, 30 0, 40 10, 30 20, 20 10))");

JAVA 读取shp数据,shp导入,导出工具

参考文章:https://blog.nowcoder.net/n/6a298f8a0dc34d988e76becb5954fa8d

JTS Geometry用例分析

一些比较常用的方法使用

参考文章:https://blog.csdn.net/qq_18298439/article/details/104427065

凸包算法:找出一堆点的边界数据

参考文章:https://blog.csdn.net/hn_lzh2014/article/details/129009157

发布TIFF和Shp服务

发布TIFF参考文章:https://blog.csdn.net/zl15145428/article/details/116651523

发布Shp参考文章:https://blog.csdn.net/dahongdahong/article/details/51858527

发布Shp详细文章:https://blog.csdn.net/qq_36871430/article/details/128664671

发布Shp更全面详细的一篇:https://blog.csdn.net/qq_31832209/article/details/111561350

    public String publishGeoTIFF() throws MalformedURLException, FileNotFoundException {
        String result = "";
        String url = "http://192.168.2.20:9080/geoserver";
        String username = "admin";
        String password = "geoserver";
        String filePath = "E:\\测试数据\\test-00.tif";
        try {
            GeoServerRESTReader reader = new GeoServerRESTReader(url, username, password);
            GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(url, username, password);
            List<String> workspaces = reader.getWorkspaceNames();
            if (!workspaces.contains("PJZ")) {
                boolean createws = publisher.createWorkspace("PJZ");
                System.out.println("create ws : " + createws);
            } else {
                result = "workspace已经存在了,ws :" + "PJZ";
            }
            //判断数据存储(datastore)是否已经存在,不存在则创建
            RESTDataStore restStore = reader.getDatastore("PJZ", "storeName");
            if (restStore == null) {
                boolean publish = publisher.publishGeoTIFF("PJZ", "storeName", 							"storeName", new File(filePath), "EPSG:4326",
                GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED, "styleName", null);
                result = "publish (TIFF文件发布状态) : " + publish;
            } else {
                result = "数据存储已经存在了,store:" + "storeName";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
public String publishShp(String workSpace, String storeName, String layername, String filePath) {
        String result="";
        try {
            File zipFile=new File(filePath);
            GeoServerRESTReader reader = new GeoServerRESTReader(url, username, password);
            GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(url, username, password);
            List<String> workspaces=reader.getWorkspaceNames();
            if(workspaces.contains(workSpace)){
                if(publisher.publishShp(workSpace, storeName, layername, zipFile, "EPSG:4326")){
                    result="发布成功!";
                }else{
                    result="发布失败!";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

根据wkt生成shp文件

 /**
     * 生成shp文件
     * @param wkt wkt格式 经纬度必须首尾相连
     * @param geoType 创建shp的类型
     * @throws IOException
     * @throws FactoryException
     */
    public static void writeShape(String wkt,String geoType) throws IOException, FactoryException {

//        wkt = "{\"msg\":\"操作成功\", \"code\":\"200\", \"data\":{\"area\":9905.214292325567, \"WKT\":\"POLYGON((115.5374 36.6232,115.5384 36.6230,115.5381 36.6217,115.5371 36.6219,115.5374 36.6232))\"}}";
        JSONObject jsonObject = JSONObject.parseObject(wkt);
        String WKT = jsonObject.getJSONObject("data").getString("WKT");
        String substring = WKT.substring(9, WKT.length() - 2);
        String[] split = substring.split(",");
        List<polygonPoint> locations = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            String[] s = split[i].split(" ");
            locations.add(new polygonPoint(Double.parseDouble(s[0]), Double.parseDouble(s[1])));
        }
        // create simple feature builder for the locations
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("Feature");
        /**
         *  //方式一
         *	CRS.decode("EPSG:4326");
         *  //方式二
         *	DefaultGeographicCRS.WGS84;
         *
         *  EPSG:4490为大地坐标系_国家2000大地坐标系CGCS2000
         *  EPSG:4326支持一种默认的定义方式, 坐标系WGS84
         */
//        builder.setCRS(DefaultGeographicCRS.WGS84);
        builder.setCRS(CRS.decode("EPSG:4326"));
		//添加自定义参数
        builder.add("name", String.class);
        //判断geoType类型
        if ("Polygon".equals(geoType) || "polygon".equals(geoType)) {
            builder.add("the_geom", Polygon.class);
        } else if ("MultiPolygon".equals(geoType)) {
            builder.add("the_geom", MultiPolygon.class);
        } else if ("Point".equals(geoType) || "point".equals(geoType)) {
            builder.add("the_geom", Point.class);
        } else if ("MultiPoint".equals(geoType)) {
            builder.add("the_geom", MultiPoint.class);
        } else if ("LineString".equals(geoType)) {
            builder.add("the_geom", LineString.class);
        } else if ("MultiLineString".equals(geoType) || "Polyline".equals(geoType) || "polyline".equals(geoType)) {
            builder.add("the_geom", MultiLineString.class);
        } else {
            throw new Exception("Geometry中没有该类型:" + geoType);
        }
        
        SimpleFeatureType featureType = builder.buildFeatureType();
//        DefaultFeatureCollection collection = new DefaultFeatureCollection();
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
//        SimpleFeature feature = toFeature(locations, featureType, geometryFactory);
        DefaultFeatureCollection collection = toFeature(wkt, featureType, geometryFactory,geoType);
//        collection.add(feature);
//        collection.forEach(name -> System.out.println(name));
        /**
         * Degub print in this point looks like this:
         * SimpleFeatureImpl:polygonFeature=[SimpleFeatureImpl.Attribute:
         * polygon<polygon id=fid-77f7c041_174f9627c85_-8000>=polyGON
         * ((60.15396170672204 24.665516804291176,* 60.156868902093464 24.684907435753292))]
         * So looks okay still...
         */

        File shapeFile = new File(new File("").getAbsolutePath() +
                "\\ruoyi-admin\\src\\main\\resources\\shp\\shapefile.shp");
        Map<String, Serializable> params = new HashMap<>();
        params.put("url", shapeFile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);
        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
        ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        //参数设置字符集
        dataStore.setCharset(StandardCharsets.UTF_8);
        dataStore.createSchema(featureType);
        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);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();
                zipShapeFile(shapeFile.getPath());
                logger.info("生成shp文件成功:"+shapeFile.getAbsolutePath());
            } catch (Exception problem) {
                transaction.rollback();
            } finally {
                transaction.close();
            }
        }
    }

/**
     * 创建要素
     *
     * @param wkt
     * @param featureType
     * @param geometryFactory
     * @return
     */
    public static DefaultFeatureCollection toFeature(String wkt, SimpleFeatureType featureType,GeometryFactory geometryFactory, String geoType) throws Exception {
//通过坐标对象Coordinate创建
//        Coordinate[] coords = new Coordinate[locations.size()];
//        int i = 0;
//        for (MyPoint location : locations) {
//            Coordinate coord = new Coordinate(location.getX(), location.getY(), 0);
//            coords[i] = (coord);
//            i++;
//        }
//        Polygon polygon = geometryFactory.createPolygon(coords);

        //通过WKT创建
        WKTReader reader = new WKTReader(geometryFactory);
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
        DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
        if ("Polygon".equals(geoType) || "polygon".equals(geoType)) {
            Polygon polygon = (Polygon) reader.read(wkt);
            featureBuilder.add(polygon);
        } else if ("MultiPolygon".equals(geoType)) {
            MultiPolygon multiPolygon = (MultiPolygon) reader.read(wkt);
            for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
                Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
                //自定义参数传入
                featureBuilder.add("name");

                featureBuilder.add(polygon);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                featureCollection.add(feature);
            }
            return featureCollection;
        } else if ("Point".equals(geoType) || "point".equals(geoType)) {
            Point point = (Point) reader.read(wkt);
            featureBuilder.add(point);
        } else if ("MultiPoint".equals(geoType)) {
            MultiPoint multiPoint = (MultiPoint) reader.read(wkt);
            featureBuilder.add(multiPoint);
        } else if ("LineString".equals(geoType)) {
            LineString lineString = (LineString) reader.read(wkt);
            featureBuilder.add(lineString);
        } else if ("MultiLineString".equals(geoType) || "Polyline".equals(geoType) || "polyline".equals(geoType)) {
            MultiLineString multiLineString = (MultiLineString) reader.read(wkt);
            int index = -1;
            for (int i = 0; i < multiLineString.getNumGeometries(); i++) {
                LineString lineString = (LineString) multiLineString.getGeometryN(i);
                //自定义参数传入
                featureBuilder.add("name");

                featureBuilder.add(lineString);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                featureCollection.add(feature);
            }
            return featureCollection;
        } else {
            throw new Exception("Geometry中没有该类型:" + geoType);
        }
        featureCollection.add(featureBuilder.buildFeature(null));
        return featureCollection;

    }

【GeoTools】polygon 转 multipolygon

参考文章:https://blog.csdn.net/u013517229/article/details/105790292

    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory( null );
    WKTReader reader = new WKTReader( geometryFactory );
    Polygon p = (Polygon) reader.read("POLYGON ((115.05948119466 22.8626134301296, 115.06225289824 22.8626134301296, 115.06225289824 22.8523347587268, 115.05925618009766 22.85237940437907, 115.05948119466 22.8626134301296))");
    GeometryFactory gf = new GeometryFactory();
    MultiPolygon mPoly = null;
    if (p instanceof Polygon){
        Polygon[] polys = new Polygon[1];
        polys[0] = p;
        mPoly = gf.createMultiPolygon(polys);
    }
    System.out.println(mPoly);

java删除已经发布的Geotiff服务

参考文章:https://www.jianshu.com/p/efb734e36443

import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;

public class UnpublishGeotiff {
    public static void main(String[] args) throws Exception{
        final String geoserverUrl = "http://localhost:8080/geoserver";
        final String geoserverUsername = "admin";
        final String geoserverPassword = "geoserver";

        GeoServerRESTPublisher geoServerRESTPublisher = new GeoServerRESTPublisher(geoserverUrl,geoserverUsername,geoserverPassword);
        GeoServerRESTReader geoServerRESTReader = new GeoServerRESTReader(geoserverUrl,geoserverUsername,geoserverPassword);

        String workspace = "bbb";
        String storeName = "resttestdem";
        String coverageName = "resttestdem";

        // 测试coveragestore是否存在
        boolean coveragestoreNull = geoServerRESTReader.existsCoveragestore(workspace, storeName);
        System.out.println("coveragestore是否存在:"+coveragestoreNull);

        // 测试coverage是否存在
        boolean coverageNull = geoServerRESTReader.existsCoverage(workspace, storeName, coverageName);
        System.out.println("coverage是否存在:"+coverageNull);

        //删除coverage
        boolean coverageResult = geoServerRESTPublisher.unpublishCoverage(workspace, storeName, coverageName);
        System.out.println("coverage删除成功:"+coverageResult);

        //删除coveragestore
        boolean coveragestoreResult = geoServerRESTPublisher.removeCoverageStore(workspace, storeName,true);
        System.out.println("coveragestore删除成功:"+coveragestoreResult);

        // 测试coveragestore是否存在
        boolean coveragestoreNull2 = geoServerRESTReader.existsCoveragestore(workspace, storeName);
        System.out.println("coveragestore是否存在:"+coveragestoreNull2);

        // 测试coverage是否存在
        boolean coverageNull2 = geoServerRESTReader.existsCoverage(workspace, storeName, coverageName);
        System.out.println("coverage是否存在:"+coverageNull2);
    }
}

压缩shp文件

/**
 * 压缩shape文件
 *
 * @param shpPath shape文件路径(包含shape文件名称)
 */
public static void zipShapeFile(String shpPath) {
    try {
        File shpFile = new File(shpPath);
        String shpRoot = shpFile.getParentFile().getPath();
        String shpName = shpFile.getName().substring(0, shpFile.getName().lastIndexOf("."));

        String zipPath = shpRoot + File.separator + shpName + ".zip";
        File zipFile = new File(zipPath);
        InputStream input = null;
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        // zip的名称为
        zipOut.setComment(shpName);
        String[] shpFiles = new String[]{
                shpRoot + File.separator + shpName + ".dbf",
                shpRoot + File.separator + shpName + ".prj",
                shpRoot + File.separator + shpName + ".shp",
                shpRoot + File.separator + shpName + ".shx",
                shpRoot + File.separator + shpName + ".fix"
        };

        for (int i = 0; i < shpFiles.length; i++) {
            File file = new File(shpFiles[i]);
            input = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(file.getName()));
            int temp = 0;
            while ((temp = input.read()) != -1) {
                zipOut.write(temp);
            }
            input.close();
        }
        zipOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

解压缩文件

/**
 *文件解压缩
 * @param zipfile 要解压缩的zip文件
 * @param destpath 解压后文件所放的目录,需要"D:\\"或"D:\\test\"格式 注意最后需要/
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void unzip(String zipfile, String destpath) throws IOException {
    zipfile = "D:\\ideaProject\\RuoYi-Vue\\ruoyi-admin\\src\\main\\resources\\shp\\shapefile.zip";
    destpath = "D:\\shp\\";
    try {
        File zipFile = new File(zipfile);
        if (!zipFile.exists()) {
            throw new IOException("要解压的压缩文件不存在");
        }
        File pathFile = new File(destpath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        FileInputStream fis = new FileInputStream(zipfile);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry z1 = null;
        while ((z1 = zis.getNextEntry()) != null) {
            if (z1.isDirectory()) {
                File f = new File("D:\\" + z1.getName());
                f.mkdirs();
            } else {
                String fileName = z1.getName();
                FileOutputStream fos = new FileOutputStream(destpath + fileName);
                int tmp = -1;
                while ((tmp = zis.read()) != -1) {
                    /*写入到目标文件中*/
                    fos.write(tmp);
                }
                zis.closeEntry();
                fos.close();
            }
        }
        zis.close();
    } catch (Exception e) {
        throw new IOException(e);
    }
}

读取shp文件(wkt格式)

参考文章:https://blog.csdn.net/leavesloves/article/details/120183652

/**
 *  读取shp文件
 * @param shpPath
 * @return
 * @throws IOException
 */
public static List<Map<String, Object>> readShp(String shpPath) throws IOException {
    //加载文件
    File file = new File(shpPath);
    if (file == null) {
        return null;
    }
    //map记录shapefile key-value数据
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    //通过store获取featurecollection
    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource featureSource = store.getFeatureSource();
    SimpleFeatureCollection simpleFeatureCollection = featureSource.getFeatures();
    SimpleFeatureIterator itertor = simpleFeatureCollection.features();
    //遍历featurecollection
    while (itertor.hasNext()) {
        Map<String, Object> data = new HashMap<>();
        SimpleFeature feature = itertor.next();
        Collection<Property> p = feature.getProperties();
        Iterator<Property> it = p.iterator();
        //遍历feature的properties
        while (it.hasNext()) {
            Property pro = it.next();
            String field = pro.getName().toString();
            String value = pro.getValue().toString();
            field = field.equals("the_geom") ? "wkt" : field;
            byte[] bytes = value.getBytes("iso8859-1");
            value = new String(bytes, "gbk");
            data.put(field, value);
        }
        list.add(data);
    }
    itertor.close();
    return list;
}

JTS–判断一个经纬度点是否在多边形内

参考文章:https://blog.csdn.net/weixin_54586234/article/details/126995441

import com.ruoyi.crops.service.IFarmMachineryService;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.springframework.stereotype.Service;

@Service
public class FarmMachineryServiceImpl implements IFarmMachineryService {
    /**
     * 将字符串多坐标点转换为坐标数组
     * @param latLonString "116.616634,40.272665|116.644733,40.280371|116.636181,40.264352|116.616634,40.272665"
     * @return org.locationtech.jts.geom.Coordinate[]
     */
    @Override
    public Coordinate[] getCoordinateArray(String latLonString) {
        String[] split = latLonString.split("\\|");
        Coordinate[] coordinateArray = new Coordinate[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] LatLng = split[i].split(",");
            Coordinate coordinate = new Coordinate(Double.valueOf(LatLng[0]), Double.valueOf(LatLng[1]));
            coordinateArray[i] = coordinate;
        }
        return coordinateArray;
    }

    /**
     * 判断坐标点是否在多坐标点组成的多边形面内
     *
     * @param coordinateArray
     * @param coordinate
     * @return boolean
     * @author guochao.bj@fang.com
     * within 判断是否在内部,边缘点返回false
     * intersects 判断是否相交,弥补 within边缘点缺陷,
     */
    @Override
    public boolean withinAndIntersects(Coordinate[] coordinateArray, Coordinate coordinate) {
        boolean result = false;
        //小于3个点无法组成多边形
        if (coordinateArray.length < 3) {
            return result;
        }

        //必须首尾坐标点相同组成闭合多边形
        if (!(coordinateArray[0].equals2D(coordinateArray[coordinateArray.length - 1]))) {
            return result;
        }

        GeometryFactory geometryFactory = new GeometryFactory();
        Point point = geometryFactory.createPoint(coordinate);
        Polygon polygon = geometryFactory.createPolygon(coordinateArray);

        if (point.within(polygon) || point.intersects(polygon)) {
            result = true;
        }

        return result;
    }

    /**
     * 使用这个接口 格式:"111, 111|222, 222|333, 333|444, 444|111, 111"
     * 多边形最后需拼接上第一个点的经纬度
     * @param lnglatPolygon 坐标数组
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    @Override
    public boolean withinAndIntersects(String lnglatPolygon, double lng, double lat) {
        Coordinate[] latLonMap = getCoordinateArray(lnglatPolygon);
        Coordinate coordinate = new Coordinate(lng,lat);
        boolean within = withinAndIntersects(latLonMap, coordinate);
        return within;
    }
}

判断Wkt需要发布的类型

if ("Polygon".equals(geoType) || "polygon".equals(geoType)) {
                tb.add("the_geom", Polygon.class);
            } else if ("MultiPolygon".equals(geoType)) {
                tb.add("the_geom", MultiPolygon.class);
            } else if ("Point".equals(geoType) || "point".equals(geoType)) {
                tb.add("the_geom", Point.class);
            } else if ("MultiPoint".equals(geoType)) {
                tb.add("the_geom", MultiPoint.class);
            } else if ("LineString".equals(geoType)) {
                tb.add("the_geom", LineString.class);
            } else if ("MultiLineString".equals(geoType) || "Polyline".equals(geoType) || "polyline".equals(geoType)) {
                tb.add("the_geom", MultiLineString.class);
            } else {
                throw new Exception("Geometry中没有该类型:" + geoType);
            }

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java编写一个程序,使用GeoTools库来读取您的矢量数据,并使用GeoJSON格式将其转换为瓦片。然后,您可以使用GeoServer发布这些瓦片。 下面是一个简单的Java程序,可以将矢量数据转换为GeoJSON格式的瓦片: ```java import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.store.ContentFeatureCollection; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureIterator; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.map.FeatureLayer; import org.geotools.map.MapContent; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.renderer.lite.StreamingRenderer; import org.geotools.styling.SLD; import org.geotools.styling.Style; import org.geotools.styling.StyleFactory; import org.geotools.styling.Symbolizer; import org.geotools.styling.TextSymbolizer; import org.geotools.styling.Font; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.filter.FilterFactory2; import org.opengis.filter.identity.FeatureId; public class GeoJSONTileGenerator { public static void main(String[] args) throws IOException { // Open the vector data file File file = new File("data.shp"); Map<String, Object> map = new HashMap<>(); map.put("url", file.toURI().toURL()); // Read the data into a feature collection ContentFeatureCollection features = new ContentFeatureCollection(map, null); // Create a style for the features StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); FilterFactory2 filterFactory = CommonFactoryFinder.getFilterFactory2(); Symbolizer symbolizer = styleFactory.createPolygonSymbolizer(); Style style = SLD.createPolygonStyle(java.awt.Color.BLUE, java.awt.Color.WHITE, 1.0f); TextSymbolizer textSymbolizer = styleFactory.createTextSymbolizer(); Font font = styleFactory.getDefaultFont(); textSymbolizer.setFont(font); textSymbolizer.setLabel("Name"); style.featureTypeStyles().get(0).rules().get(0).symbolizers().add(textSymbolizer); // Create a feature type for the GeoJSON output SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName("MyFeatureType"); builder.setCRS(DefaultGeographicCRS.WGS84); builder.add("geometry", Geometry.class); builder.add("Name", String.class); SimpleFeatureType featureType = builder.buildFeatureType(); // Create a GeoJSON feature writer FeatureJSON featureJSON = new FeatureJSON(); featureJSON.setEncodeNullValues(true); // Create a map content for the renderer MapContent mapContent = new MapContent(); mapContent.setTitle("My Map"); // Add the features to the map content and set the style SimpleFeatureIterator iterator = features.features(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); FeatureId id = feature.getIdentifier(); Envelope envelope = feature.getBounds(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); featureBuilder.add(geometry); featureBuilder.add(feature.getAttribute("Name")); SimpleFeature newFeature = featureBuilder.buildFeature(id.toString()); mapContent.addLayer(new FeatureLayer(newFeature, style)); } iterator.close(); // Create a renderer for the map content and set the bounding box StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mapContent); renderer.setJava2DHints(new java.util.HashMap<RenderingHints.Key,Object>()); Envelope bbox = new Envelope(-180, 180, -90, 90); double resolution = 0.1; int tileSize = 256; // Loop through the tiles and write them to GeoJSON files for (int x = 0; x < Math.pow(2, 5); x++) { for (int y = 0; y < Math.pow(2, 5); y++) { Envelope tileEnvelope = new Envelope(x * tileSize * resolution + bbox.getMinX(), (x + 1) * tileSize * resolution + bbox.getMinX(), y * tileSize * resolution + bbox.getMinY(), (y + 1) * tileSize * resolution + bbox.getMinY()); renderer.setMapContent(mapContent); renderer.paint(null, null, tileEnvelope); Geometry tileGeometry = JTSFactoryFinder.getGeometryFactory().toGeometry(tileEnvelope); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); featureBuilder.add(tileGeometry); featureBuilder.add(null); SimpleFeature feature = featureBuilder.buildFeature(null); File tileFile = new File("tile_" + x + "_" + y + ".json"); featureJSON.writeFeature(feature, tileFile); } } } } ``` 这个程序将矢量数据读取到一个特征集合中,然后为每个特征创建一个图层,并使用GeoTools渲染器将其渲染为一个GeoJSON格式的瓦片。您可以根据需要修改渲染器的参数,例如分辨率和瓦片大小。 然后,您可以使用GeoServer发布这些瓦片。首先,将它们上传到GeoServer中。然后,创建一个新的数据存储,选择“GeoJSON瓦片”作为存储类型,并选择适当的参数。最后,发布存储并选择适当的样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值