Как отфильтровать функцию используя OpenLayer и WFS? - PullRequest
0 голосов
/ 19 февраля 2020

Я могу извлечь данные из файла geo json (созданного из типа слоя GeoServer WFS) и отобразить его в браузере с помощью OpenLayer. Но я сталкиваюсь с проблемой, когда хочу отображать данные только с некоторыми функциями фильтрации.

Мое JSON имя файла -> gpr.geo json
Имя слоя GeoServer -> визуализация: GPR
Фильтр атрибутов -> branchCode = N01821 и routeCode = 0650

I последовал учебник по фильтрации от https://www.giserdqy.com/wp-content/guids/ol-v4.6.5/examples/vector-wfs-getfeature.html, и я также попытался использовать CQL_FILTER, но не повезло вообще

Ниже мой код и фильтрация не работает

var mymap = new ol.Map({
    target: 'mapid',
    layers: [
          new ol.layer.Tile({
            source: new ol.source.XYZ({
                //Vworld Tile 변경
                url: 'http://xdworld.vworld.kr:8080/2d/Base/201802/{z}/{x}/{y}.png'
            })
          })
    ],
    view: new ol.View({
        center: ol.proj.transform([128.1591, 36.4109], 'EPSG:4326', 'EPSG:3857'),
        zoom: 8,
        minZoom: 6,
        maxZoom: 19
    }),
    logo:false
});

var vectorSource = new ol.source.Vector({
    url: './data/GPR.geojson,
    format: new ol.format.GeoJSON()
})

var layer = new ol.layer.VectorImage({
    source: vectorSource,
    visible: true,
})

// generate a GetFeature request
var featureRequest = new ol.format.WFS().writeGetFeature({
    srsName: 'EPSG:3857',
    featureNS: 'visualization',
    featurePrefix: 'osm',
    featureTypes: ['GPR'],
    outputFormat: 'application/json',
    filter: ol.format.filter.and(
        ol.format.filter.like('branchCode', 'N01821'),
        ol.format.filter.equalTo('routeCode', '0650')
    )
});

// then post the request and add the received features to a layer
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    body: new XMLSerializer().serializeToString(featureRequest)
}).then(function (response) {
    return response.json();
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});

Использование Leaflet, WMS и CQL Filter очень просто, как показано ниже. Как это сделать с помощью OpenLayer и WFS?

var wmsLayer= L.tileLayer.wms("http://localhost:8080/geoserver/visualization/wms", {
layers: 'visualization:GPR',
format: 'image/png',
transparent: true,
CQL_FILTER:  "branchCode='N01821'"

1 Ответ

1 голос
/ 19 февраля 2020

Вы по-прежнему можете использовать запрос и CQL_FILTER в OL, как в примере с вашей листовкой, что-то вроде этого,

$.ajax({
    method: 'POST',
    url: 'http://localhost:8080/geoserver/visualization/wfs',
    data: {
        "service": "WFS",
        "request": "GetFeature",
        "typename": "visualization:GPR",
        "outputFormat": "application/json",
        "srsname": "EPSG:3857",
        "maxFeatures": 50,
        "CQL_FILTER": "branchCode='N01821'"
    },
    success: function (response) {
        var features = new ol.format.GeoJSON().readFeatures(response);
        vectorSource.addFeatures(features);
        mymap.getView().fit(vectorSource.getExtent());
    },
    fail: function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    }
});

Если вы предпочитаете использовать fetch, я думаю, это должно работать,

let featureRequest  = {
    "service": "WFS",
    "request": "GetFeature",
    "typename": "visualization:GPR",
    "outputFormat": "application/json",
    "srsname": "EPSG:3857",
    "maxFeatures": 50,
    "CQL_FILTER": "branchCode='N01821'"
};
fetch('http://localhost:8080/geoserver/visualization/wfs', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(featureRequest)
}).then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(reponse);
    vectorSource.addFeatures(features);
    mymap.getView().fit(vectorSource.getExtent());
});
...