Example of making a WFS GetFeature request with a filter.
This example generates a GetFeature
request which uses a PropertyIsEqualTo
and a PropertyIsLike
filter, and then posts the request to load the features that match the query.
<!DOCTYPE html>
<html lang="en">
<head>
<title>WFS - GetFeature</title>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {
equalTo as equalToFilter,
like as likeFilter,
and as andFilter
} from 'ol/format/filter';
import {WFS, GeoJSON} from 'ol/format';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import BingMaps from 'ol/source/BingMaps';
import VectorSource from 'ol/source/Vector';
import {Stroke, Style} from 'ol/style';
var vectorSource = new VectorSource();
var vector = new VectorLayer({
source: vectorSource,
style: new Style({
stroke: new Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
var raster = new TileLayer({
source: new BingMaps({
imagerySet: 'Aerial',
key: 'Your Bing Maps Key from http://www.bingmapsportal.com/ here'
})
});
var map = new Map({
layers: [raster, vector],
target: document.getElementById('map'),
view: new View({
center: [-8908887.277395891, 5381918.072437216],
maxZoom: 19,
zoom: 12
})
});
// generate a GetFeature request
var featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:3857',
featureNS: 'http://openstreemap.org',
featurePrefix: 'osm',
featureTypes: ['water_areas'],
outputFormat: 'application/json',
filter: andFilter(
likeFilter('name', 'Mississippi*'),
equalToFilter('waterway', 'riverbank')
)
});
// then post the request and add the received features to a layer
fetch('https://ahocevar.com/geoserver/wfs', {
method: 'POST',
body: new XMLSerializer().serializeToString(featureRequest)
}).then(function(response) {
return response.json();
}).then(function(json) {
var features = new GeoJSON().readFeatures(json);
vectorSource.addFeatures(features);
map.getView().fit(vectorSource.getExtent());
});
{
"name": "vector-wfs-getfeature",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}