WFS GetFeature Query – Retrieving Features from Coordinates

geoservergetfeatureopenlayerswfs

I am using Openlayers with Tiled Layers, and when I click on a map (and get the clicked coordinate), I would like to query a (GeoServer) WFS GetFeature service to see if I clicked on a Feature. (I can do something simlar in WMS but want to try to do this with WFS).

The GetFeature requests takes a bounding box as a parameter, so I was thinking I could build a bounding box based upon a coordinate somehow? This would allow the click to be a little fuzzy – you wouldn't have to click precisely on the point.

I also see there is some searching capabilities with "CQL_FILTER" I may be able to use?

let viewProjection = "EPSG:3857";

map.on("singleclick", function(evt) {

    let clickedCoordinate = evt.coordinate;

    let params = {
        service: "WFS",
        version: "1.1.0",
        request: "GetFeature",
        typename: "myWorkspace:myFeature",
        srsname: viewProjection,
        outputFormat: "application/json",
        //CQL_FILTER: CAN THIS BE USED???
        //bbox: HOW DO I BUILD A BOX AROUND THE COORDINATE??
    };

        $.ajax(url, {
            type: "GET",
            data: params,
            dataType: "json",
            contentType: "application/json; charset=utf-8"
        }).then(data => {
            // SUCCESS
        }).fail((jqXHR, textStatus, errorThrown) => {
            // FAIL
        });

    }

});

Best Answer

For getting bbox coordinates, you can get the coordinates from evt.coordinate and use pixel resolution for your zoom using https://openlayers.org/en/latest/apidoc/ol.View.html#getResolutionForZoom. Your bbox will be (if not tolerance e.g 1 pixels)

var resolutionForZoom = map.getView().getResolutionForZoom(map.getView().getZoom());
minx = evt.coordinate[0] - 0.5 * resolutionForZoom
maxx = evt.coordinate[0] + 0.5 * resolutionForZoom
miny = evt.coordinate[1] - 0.5 * resolutionForZoom
maxy = evt.coordinate[1] + 0.5 * resolutionForZoom

There are no issue filtering using CQL Filter as long as you know them enough (already done it on a project using OpenLayers and GeoServer)

Related Question