Openlayer4中实现基于Geoserver的WFS服务GetFeature的查询请求

在使用地图时,有些图层,只有在有需要的时候才进行展示,甚至希望能将带坐标的地图数据从服务器上取到本地,进行操作,进行渲染等等。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();
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值