使用Java生成shp文件-面(Polygon)

Maven依赖:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geotiff</artifactId>
            <version>25.3.01</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>25.3.01</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 中央仓库没有 gt-geotiff, gt-shapefile 指定新的仓库 -->
        <repositories>
            <repository>
                <id>GeoSolutions</id>
                <url>http://maven.geo-solutions.it/</url>
            </repository>
        </repositories>

指定仓库参考说明
Maven中GeoTools的引入 - Maven 的 repository 与 mirror_maven geotools-CSDN博客

	/**
     * 生成shape文件
     *
     * @param shpPath  生成shape文件路径(包含文件名称)
     * @param encode   编码
     * @param geoType  图幅类型,Point和Rolygon
     * @param shpKey   data中图幅的key
     * @param attrKeys 属性key集合
     * @param data     图幅和属性集合
     */
    public static void write2Shape(String shpPath, String encode, String geoType, String shpKey, List<String> attrKeys, List<Map<String, Object>> data) {
        try {
            if (data == null || data.size() == 0) 
                return;
            //创建shape文件对象
            File file = new File(shpPath);
            Map<String, Serializable> params = new HashMap<>();
            params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setCRS(DefaultGeographicCRS.WGS84);
            tb.setName("shapefile");

            if ("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)) {
                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)) {
                tb.add("the_geom", MultiLineString.class);
            } else {
                throw new Exception("Geometry中没有该类型:" + geoType);
            }

            for (String field : attrKeys) {
                tb.add(field, String.class);
            }

            ds.createSchema(tb.buildFeatureType());
            //设置编码
            Charset charset = Charset.forName(encode);
            ds.setCharset(charset);
            //设置Writer
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
            //写入文件信息
            for (int i = 0; i < data.size(); i++) {
                SimpleFeature feature = writer.next();
                Map<String, Object> row = data.get(i);
                Geometry geom = (Geometry) row.get(shpKey);
                feature.setAttribute("the_geom", geom);
                for (String key : row.keySet()) {
                    if (!key.equals(shpKey)) {
                        if (row.get(key) != null) {
                            feature.setAttribute(key, row.get(key).toString());
                        } else {
                            feature.setAttribute(key, "");
                        }
                    }
                }
            }
            writer.write();
            writer.close();
            ds.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理为几何图形(多边形)和名称的 Map 对象
     * @param rangeArray
     * @param name
     * @return
     */
    private Map<String, Object> getMap(JSONArray rangeArray, String name) {
        Coordinate[] coordinates = new Coordinate[rangeArray.size()];
        for (int i = 0; i < rangeArray.size(); i++) {
            Coordinate coordinate = new Coordinate();
            coordinate.x = rangeArray.getJSONArray(i).getDouble(0);
            coordinate.y = rangeArray.getJSONArray(i).getDouble(1);
            coordinates[i] = coordinate;
        }
        //  创建一个多边形(Polygon)对象 geometry,该多边形由 coordinates 数组中的坐标点组成。
        Geometry geometry = new GeometryFactory().createPolygon(coordinates);
        Map<String, Object> map1 = new HashMap<>();
        // 设置属性设置值
        map1.put("name", name);
        map1.put("geom", geometry);
        return map1;
    }





    /**
     * 生成地块的shp文件
     */
    @Test
    public void getSharp() {
        // 最终图层List
        List<Map<String, Object>> data = new ArrayList<>();
        // 获取地块列表的JSON
        String json = FileUtil.readString("C:\\Users\\xxx\\Desktop\\json.json", StandardCharsets.UTF_8);

        JSONArray baseArray = JSONObject.parseArray(json);
        for (int i = 0; i < baseArray.size(); i++) {
            // 解析数据源
            JSONObject jsonObject = baseArray.getJSONObject(i);
            String plotName = jsonObject.get("plot_name").toString();
            // 经纬度二维数组
            // 注: 需要注意的是这里需要是一个封闭的空间, ====即首尾坐标相同====
            JSONArray range = jsonObject.getJSONArray("plot_range");
            // 注: 这里设置地块名是因为后面想根据不同的地块名这个属性上色,所以给每个地块设置了属性。便于根据地块名设置颜色。 如果没有这个需求可以不处理为空
            Map<String, Object> map = getMap(range, plotName);
            data.add(map);
        }

        List<String> list = new ArrayList<>();
        list.add("name");
        write2Shape("C:\\Users\\xxx\\Desktop\\shp-new\\plot.shp", "utf-8", "MultiPolygon", "geom", list, data);

    }

执行可以看到在文件夹中有以下五个文件

在这里插入图片描述

在ArcMap中打开shp查看

选择展示属性

得到如下图片:
在这里插入图片描述

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java可以利用开源库GeoTools生成shp文件。GeoTools是一个开发平台,用于处理空间数据。它提供了丰富的API来读取、写入和操作各种GIS数据格式,包括矢量数据格式(如Shapefile、GML、KML等)和栅格数据格式(如GeoTIFF、NetCDF等)。 要使用GeoTools生成shp文件,您需要在Java项目中添加GeoTools的库文件。接着,您需要创建一个FeatureCollection对象,该对象将包含要在shp文件中写入的所有矢量要素(例如点、线、多边形等)。要创建FeatureCollection对象,您可以使用DefaultFeatureCollection类。 然后,您需要使用FeatureTypeBuilder类创建FeatureType对象。 FeatureType定义要素的结构,包括属性名称、数据类型和坐标参考系等。最后,您可以使用FeatureBuilder类将要素添加到FeatureCollection对象中,并调用FeatureWriter类将FeatureCollection写入shp文件。 例如,以下是使用GeoTools在Java中创建一个包含两个点的shp文件的示例: ``` CoordinateReferenceSystem crs = CRS.decode("EPSG:4326"); SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName("Location"); builder.setCRS(crs); builder.add("the_geom", Point.class); builder.add("name", String.class); SimpleFeatureType featureType = builder.buildFeatureType(); DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("locations", featureType); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); Point point1 = geometryFactory.createPoint(new Coordinate(2.0, 1.0)); featureBuilder.set("the_geom", point1); featureBuilder.set("name", "Point 1"); SimpleFeature feature1 = featureBuilder.buildFeature(null); Point point2 = geometryFactory.createPoint(new Coordinate(4.0, 3.0)); featureBuilder.set("the_geom", point2); featureBuilder.set("name", "Point 2"); SimpleFeature feature2 = featureBuilder.buildFeature(null); featureCollection.add(feature1); featureCollection.add(feature2); File newFile = new File("locations.shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); dataStore.createSchema(featureType); String typeName = dataStore.getTypeNames()[0]; FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = dataStore.getFeatureWriter(typeName, Transaction.AUTO_COMMIT); try { while (featureCollection.features().hasNext()) { SimpleFeature feature = featureCollection.features().next(); SimpleFeature copy = featureWriter.next(); copy.setAttributes(feature.getAttributes()); featureWriter.write(); } } finally { featureWriter.close(); dataStore.dispose(); } ``` 在此示例中,我们创建了包含两个点的FeatureCollection对象。它们分别被命名为“Point 1”和“Point 2”。我们还使用CoordinateReferenceSystem对象定义了编码为“EPSG:4326”的坐标参考系。最后,我们使用ShapefileDataStore类将FeatureCollection对象写入名为“locations”的shp文件中。 总之,使用GeoTools可以方便地在Java生成shp文件。它为开发人员提供了强大且易于使用的API,可以生成各种GIS数据格式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yfs1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值