GeoTools 结合 OpenLayers 实现属性查询(二)

关注我,带你一起学GIS ^

前言

在GIS开发中,属性查询是非常普遍的操作,这是每一个GISer都要掌握的必备技能。实现高效的数据查询功能可以提升用户体验,完成数据的快速可视化表达。

本篇教程基于前一篇文章GeoTools 结合 OpenLayers 实现属性查询进行优化完善(如果你还没有看过,请从那里开始),讲解如何将使用GeoTools工具结合OpenLayers实现PostGIS空间数据库数据的属性查询功能,着重说明从后端读取FeatureCollection对象在前端直接加载。

1. 后端转换FeatureCollection对象

在本例中通过创建一个FeatureJSON和一个StringWriter对象,将FeatureCollection数据转换为GeoJSON字符串返回给前端。

// 创建 FeatureJSON 对象
FeatureJSON featureJSON = new FeatureJSON();
StringWriter writer = new StringWriter();
featureJSON.writeFeatureCollection(collection,writer);
// 将 FeatureCollection 转换为JSON 字符串
String jsonFeatures = writer.toString();
result.put("countries",jsonFeatures);

与前面文章例子中不同的是使用此种方法不需要创建实体对象,也不需要像下面这样遍历要素集合,然后构造要素属性,直接返回一个json字符串即可,使用起来就显得方便简单。

try(FeatureIterator<SimpleFeature> features = collection.features()) {
    while (features.hasNext()) {
        SimpleFeature feature = features.next();
        Countries country = new Countries();
        country.setGid((Integer) feature.getAttribute("gid"));
        // 此处构造要素属性数据  

        Object geometry = feature.getAttribute("geom");
        GeometryJSON geometryJSON = new GeometryJSON();
        StringWriter writer = new StringWriter();

        geometryJSON.write((Geometry) geometry,writer);
        String geoJSON = writer.toString();

        country.setGeom(geoJSON);
        countries.add(country);
    }
}catch (Exception e){
   e.printStackTrace();
}

代码修改前后对比图。

2. 前端读取FeatureCollection对象

使用此种方式在前端加载数据时也需要改写一下,主要有三个注意的点:一方面是因为后端返回的是JSON字符串数据,所以前端加载时需要使用JSON.parse方法将其解析为JSON对象;另外一方面是使用features.forEach遍历集合要素设置动态颜色值,最后是使用readFeatures方法读取FeatureCollection对象。

const countries = JSON.parse(result.countries)
// 设置动态颜色属性
countries.features.forEach(feat => {
    feat.properties.color = `hsl(${Math.floor(Math.random() * 360)}, 100%, 50%)`
})
// 读取 FeatureCollection 数据
const features = new ol.format.GeoJSON().readFeatures(countries)
const vectorSource = new ol.source.Vector({
    features: features,
    format: new ol.format.GeoJSON()
})

代码修改前后对比图。

OpenLayers示例数据下载,请在公众号后台回复:ol数据

全国信息化工程师-GIS 应用水平考试资料,请在公众号后台回复:GIS考试

GIS之路公众号已经接入了智能助手,欢迎大家前来提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏+关注 

本号不定时更新有关 GIS开发  相关内容,欢迎关注 

 

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部