在使用地圖時,有些圖層,只有在有需要的時候才進行展示,甚至希望能將帶座標的地圖數據從服務器上取到本地,進行操作,進行渲染等等。WFS服務可以滿足這一需求。
WFS服務怎麼創建?其實同WMS一樣,可以在Geoserver中進行發佈。發佈的過程,網上非常多。以下簡單記錄下,在服務發佈後,使用Openlayers來調用WFS服務的方法。
常用的有兩種方法:
1、利用Openlayers4封裝的類ol.format.WFS()
這種方法比較簡便,對於從GIS專業轉前端的可能更好理解。
2、利用ajax進行數據請求
這種方法可能前端開發同學使用的比較多
以上兩種方式的示例代碼如下:
//定義數據源爲矢量數據源
var vectorSource = new ol.source.Vector();
//定義矢量圖層
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
name: 'vector'
});
//定義樣式
var mystyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#ffff00",
width:2
})
});
//以ol4方式加載WFS圖層
function getFeaturesByOl4(){
clearLayer();
var request = new ol.format.WFS().writeGetFeature({
srcName:"EPSG:4326",
featureNS:"http://localhost:8080/geoserver/chinaNS/wfs",
featureTypes:['chinaNS:heliu'],
outputFormat: 'application/json'
})
fetch("http://localhost:8080/geoserver/chinaNS/wfs",{
method: "POST",
body: new XMLSerializer().serializeToString(request)
}).then(function(response){
return response.json();
}).then(function(json){
features = new ol.format.GeoJSON().readFeatures(json);
vectorSource.addFeatures(features);
})
}
//以ajax方式加載WFS圖層
function getFeaturesByAjax(){
clearLayer();
var data = {
"service": "wfs",
"version": "1.1.0",
"request": "GetFeature",
"typeName": "chinaNS:heliu",
"outputFormat": "application/json",
};
$.when(
$.ajax({
url: "http://localhost:8080/geoserver/chinaNS/wfs",
data: data,
type: "GET",
contentType: "text/plain;charset=UTF-8",
})
)
.done(function(response){
var json = response;
features = new ol.format.GeoJSON().readFeatures(json);
vectorSource.addFeatures(features);
})
}
// 清理矢量圖層
function clearLayer(){
map.removeLayer(vectorLayer);
map.addLayer(vectorLayer);
vectorSource.clear();
}