meface/docs/article/gis/geotools/04FeatureQuery.md

72 lines
2.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: GeoTools 要素查询
date: 2023-12-22
author: ac
categories:
- GIS
tags:
- GeoTools
---
## GeoTools 要素查询
### 1.简介
本文介绍用于查询`DataStores`数据存储(如`shapefiles`、数据库和`Web Feature Servers`)的`Filter API`。
个人观点Java关于`JDBC`的一些概念,与`GeoTools`中的类的对应关系如下:
| GeoTools | JDBC | |
|:--------------------- |:------------------- | ----------- |
| `FeatureStore` | `Connection` | 数据库连接 |
| `FeatureSource` | `PreparedStatement` | `Table` |
| `FeatureCollection` | `ResultSet` | 结果集 |
| `AttributeDescriptor` | `ResultSetMetaData` | 结果集元数据(属性列) |
| `FeatureIterator` | | |
示例:
```java
String shpPath = "D:\\demo\\tutorial\\data\\china\\330000.shp";
File shpFile = new File(shpPath);
ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpFile.toURI().toURL());
// 设置编码,防止属性的中文字符出现乱码
shapefileDataStore.setCharset(Charset.forName("UTF-8"));
// 获取文件名
String typeName = shapefileDataStore.getTypeNames()[0];
// 通过文件名在数据存储中找到对应的featuresourcetable
FeatureSource featuresource = shapefileDataStore.getFeatureSource(typeName);
// 属性查询
// Filter filter = CQL.toFilter("adcode = 330100");
// Filter filter = CQL.toFilter("name like '%州市%' and childrenNu >8");
// 空间查询
// CQL.toCQL()
Filter filter = CQL.toFilter("BBOX(the_geom, 118.77, 119.626, 28.908, 29.653)");
SimpleFeatureCollection features = (SimpleFeatureCollection)featuresource.getFeatures(filter);
int count = features.size();
System.out.println("查询结果数量:"+count);
// 获取当前矢量数据有哪些属性字段值
List<AttributeDescriptor> attributes = features.getSchema().getAttributeDescriptors();
// 拿到迭代器
SimpleFeatureIterator simpleFeatureIterator = features.features();
// 遍历每一个要素
while(simpleFeatureIterator.hasNext()) {
SimpleFeature simpleFeature = simpleFeatureIterator.next();
System.out.println("-----------分割线-------------");
// java8新特性流api
attributes.stream().forEach((a) -> {
// 依次读取这个shape中每一个属性值当然这个属性值可以处理其它业务
System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));
});
}
```
从上述可以看到,不管是什么类型的数据源,访问的顺序是先通过`FeatureStore`连接数据源,然后从`store`中获取`FeatureSource`(类似于表),最后通过`cql`类来构建查询条件传入`FeatureSource`的`getFeatures`方法中,可以得到满足条件的要素集`FeatureCollection`。