在通过openlayers请求geoserver发布的WFS地图服务时,有时需要对请求的地图做一些过滤,选择需要加载的矢量数据。
在openlayers官网案例中,关于WFS的过滤只有属性过滤,缺少空间过滤,在空间过滤时,需要对构建的多边形进行投影转换,然后再引入到过滤方法中。
例如构建一个多边形:
var polygon1=new Polygon([[
[117.12499999999999, 31.00586290462421],
[117.12499999999999, 32.091882620021806],
[116.90551757812499, 32.091882620021806],
[116.90551757812499, 31.00586290462421],
[117.12499999999999, 31.00586290462421]]]);
构建完多边形时,需要使用applyTransform进行投影转换
polygon1.applyTransform(getTransforms('EPSG:4326','EPSG:3857'));
接着发送WFS请求,并带入多边形矢量信息进行空间过滤,这里示例为intersects相交查询
const featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:3857', //投影坐标
featureNS: 'http://localhost/map', //自己的工作区命名空间URL
featurePrefix: 'osm',
featureTypes: ['xxxxx'], //需要查询的图层名称
outputFormat: 'application/json',
filter:
intersects('the_geom',polygon1) //相交查询
});
有些同学不理解featureNS的值,一般在下图的位置寻找:
下面附上完整代码:
const vectorSource = new VectorSource();
const vector = new VectorLayer({
source: vectorSource,
style: new Style({
stroke: new Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2,
}),
}),
});
this.map.addLayer(vector);
var polygon1=new Polygon([[
[117.12499999999999, 31.00586290462421],
[117.12499999999999, 32.091882620021806],
[116.90551757812499, 32.091882620021806],
[116.90551757812499, 31.00586290462421],
[117.12499999999999, 31.00586290462421]]]);
//需要将构建的面要素进行坐标转换,变成一个polygon要素
polygon1.applyTransform(getTransformss('EPSG:4326','EPSG:3857'));
const featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:3857',
featureNS: 'http://localhost/map',
featurePrefix: 'osm',
featureTypes: ['xxxxx'],
outputFormat: 'application/json',
filter:
// equalToFilter('region', '澳门特别行政区')
// andFilter(
// likeFilter('SCENEDATE', '2022/3/*'),
// equalToFilter('region', '安徽省')
// ),
intersects('the_geom',polygon1)
// equalToFilter('SCENEDATE', '2013/5/21')
});
var that = this.map
fetch('http://localhost:8080/geoserver/map/wfs', {
method: 'POST',
body: new XMLSerializer().serializeToString(featureRequest),
})
.then(function (response) {
return response.json()
})
.then(function (json) {
const features = new GeoJSON().readFeatures(json);
vectorSource.addFeatures(features);
that.getView().fit(vectorSource.getExtent());
});
在openlayers官网中,还有很多查询,基本上都大同小异,大家可以自行查询。