[GIS] How to add a PostGIS query result to OpenLayers

openlayers-2postgis

I'm doing a query on PostGIS that returns a lot of geoemtries as results (more than 1000 which is why I can't use Geoserver CQL) – the query WHERE CLAUSE is being changed each time by the user (its some kind of filter with UI form)

What is the best way to add this dynamic query result to map in OpenLayers?

Best Answer

You can change the where clause from client side using user specified parameters. The basic concept is to create query at client side(You can create it in server side too. Here I have use javascript you may use server side language like java taking input from user and doing some validation).

This function is cqlfilter which changes the picture of map you are displaying: Here, I have used different params like valone and operatorValue as input to cql text. Then finally I have merged it to create a CQL filter.You can do similar.

function CQLFilter() {
    var cql = jQuery("#valone").val() + " " + jQuery("#operatorValue").val() + " '" + jQuery("#searchFeatureVal").val() + "'";
    layerone.mergeNewParams({'CQL_FILTER': cql});
}

Also if you want to get result in the form of json or any other geoserver supported format you need to use wfs.

example:

function searchData() {
    var dataURL = dataBaseURL + "/wfs?service=wfs&version=1.0&request=GetFeature&typename=" + jQuery("#layerSelectMenu").val();
    //console.log("The data URL "+dataURL);
    var cql = "";
    var wfs = new OpenLayers.Protocol.HTTP({
        url: dataURL,
        format: new OpenLayers.Format.GML.v3({})
    });
    if (jQuery("#searchFeatureVal").val() === "") {
        cql = "";
        console.log("CQL is blank");
    } else {

        cql = jQuery("#layerColsMenu").val() + " " + jQuery("#operatorVal").val() + " '" + jQuery("#searchFeatureVal").val() + "'";
        //console.log("CQL is " + dataURL + " " + cql);
        wfs.read({
            params: {
                "CQL_FILTER": cql
            },
            callback: this.didFetchWfsFeatures
        });
    }
}