Java使用Geotools读取shape矢量数据

作为GIS开发者而言,矢量数据是我们经常要用到的,而shape数据是矢量数据中最常用的格式,因此解析shape数据也是作为GIS软件开发人员必备的基础技能,而GeoTools无疑是Java最好用来处理GIS数据的三方库,当然这只是GeoTools的冰山一角,后面我也会慢慢的去分享GeoTools的更多用法。

今天就简单来梳理下shape数据的解析获取,环境是maven工程,首先是maven依赖:

<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>
  <groupId>org.dudu.liuyang</groupId>
  <artifactId>gis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
 
 <repositories>
   <repository>
        <id>central</id>
        <name>aliyun maven</name>
        <url>https://maven.aliyun.com/repository/central</url>
        <snapshots>
        <enabled>false</enabled>
       </snapshots>
       <releases>
        <enabled>true</enabled>
       </releases>
  </repository>

  <repository>
       <id>osgeo-releases</id>
       <name>OSGeo Nexus 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-snapshots</id>
       <name>OSGeo Nexus Snapshot Repository</name>
       <url>https://repo.osgeo.org/repository/snapshot/</url>
       <snapshots>
        <enabled>false</enabled>
       </snapshots>
       <releases>
        <enabled>true</enabled>
       </releases>
  </repository>
   
   <repository>
      <id>geosolutions</id>
      <name>geosolutions repository</name>
      <url>https://maven.geo-solutions.it/</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
     <releases>
       <enabled>true</enabled>
     </releases>
    </repository>
 </repositories>
 
 
 
  <dependencies>
     <dependency>
         <groupId>org.geotools</groupId>
        <artifactId>gt-shapefile</artifactId>
        <version>25.2</version>
     </dependency>
  </dependencies>
  

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.8.RELEASE</version>
            </plugin>
        </plugins>
    </build>
  
</project>

View Code

下面就是简单的代码操作,其实如果只是简单的读取,就很简单,下面是主要代码。

package gis;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

/**
 * shape文件读取
 * @author ly
 *
 */
public class ShapeFileReaderTest {

    private static final String FILE_PATH = "F:\\data\\vector\\shape\\line\\xian_sheng.shp";
    
    public static void main(String[] args) {
        File file = new File(FILE_PATH);
        readShapeFile(file);
    }
    
    /**
     * 
     * @param shpFile  传递的是shape文件中的.shp文件
     */
    private static void readShapeFile(File shpFile) {
        /**
         * 直接使用shapefileDatastore,如果不知道,也可以使用工厂模式(见下个方法)
         * 建议,如果确定是shape文件,就直使用shapefileDatastore
         */
        try {
            ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpFile.toURI().toURL());
            //这个typeNamae不传递,默认是文件名称
            FeatureSource featuresource = shapefileDataStore.getFeatureSource(shapefileDataStore.getTypeNames()[0]);
            //读取bbox
            ReferencedEnvelope bbox  =featuresource.getBounds();
            //读取投影
            CoordinateReferenceSystem crs = featuresource.getSchema().getCoordinateReferenceSystem();
            //特征总数
            int count = featuresource.getCount(Query.ALL);
            //获取当前数据的geometry类型(点、线、面)
            GeometryType geometryType = featuresource.getSchema().getGeometryDescriptor().getType();
            //读取要素
            SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featuresource.getFeatures();
            //获取当前矢量数据有哪些属性字段值
            List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
            //
            SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
            //
            while(simpleFeatureIterator.hasNext()) {
                SimpleFeature simpleFeature = simpleFeatureIterator.next();
                attributes.stream().forEach((a) -> {
                    //依次读取这个shape中每一个属性值,当然这个属性值,可以处理其它业务
                    System.out.println(simpleFeature.getAttribute(a.getLocalName()));
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
}

View Code

当然GeoTools对于shape数据的操作非常多,除了简单的读取,还有高级的过滤查询,当然这个就需要借助ECSQL(其实在我看来就是sql语句的条件查询,只是用一种标准把它定义了出来),还有就是对矢量数据的增删改查,这些我都会在后期逐个分享。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java读取Shapefile并将多个几何体转换为多边形,你可以使用GeoTools库。以下是一个示例代码: 首先,确保你已经将GeoTools库添加到你的项目中。你可以从GeoTools的官方网站(https://geotools.org/)下载并导入相关的jar文件。 ```java import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.FeatureSource; import org.geotools.data.FileDataStore; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.feature.FeatureIterator; import org.geotools.feature.simple.SimpleFeatureImpl; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Polygon; import java.io.File; import java.util.HashMap; import java.util.Map; public class ShapefileReader { public static void main(String[] args) { String shapefilePath = "/path/to/shapefile.shp"; // 替换为你的Shapefile路径 try { // 打开Shapefile File shapefile = new File(shapefilePath); Map<String, Object> map = new HashMap<>(); map.put("url", shapefile.toURI().toURL()); DataStore dataStore = DataStoreFinder.getDataStore(map); String typeName = dataStore.getTypeNames()[0]; FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(typeName); SimpleFeatureType schema = featureSource.getSchema(); CoordinateReferenceSystem crs = schema.getCoordinateReferenceSystem(); // 获取特征迭代器并遍历每个特征 FeatureIterator<SimpleFeature> iterator = featureSource.getFeatures().features(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); // 将Geometry转换为Polygon或MultiPolygon if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; // 处理多边形 } else if (geometry instanceof MultiPolygon) { MultiPolygon multiPolygon = (MultiPolygon) geometry; // 处理多面 } } iterator.close(); // 关闭Shapefile dataStore.dispose(); } catch (Exception e) { e.printStackTrace(); } } } ``` 将`/path/to/shapefile.shp`替换为你的Shapefile的实际路径。代码会打开Shapefile,并获取特征源和特征迭代器。然后,它将遍历每个特征,并将其几何体转换为多边形(Polygon)或多面(MultiPolygon)。你可以在相关的注释部分实现你的具体逻辑。 请注意,这个示例假设Shapefile使用的是WGS84坐标参考系统。如果你的Shapefile使用其他坐标参考系统(CRS),你可能需要进行相应的坐标转换。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值