wiki:GetFeatureInfo

OpenLayers 2 is outdated. Go to the latest 3.x version: http://openlayers.org/

GetFeatureInfo

Brent Pedersen indirectly gave me the idea to start the User Recipes after he had offer up his solution to the email list.

Starting with findLayerClick(), which takes in an event and then packages up an URL to send to the WMS server using GetFeatureInfo instead of GetMap.

/*
 * An event occurred so now drill down the layers to get the info
 */
function findLayerClick(event) {

    layerlist = "here,there,everywhere";

    mouseLoc = map.getLonLatFromPixel(event.xy);

    var url = prox.getFullRequestString({
                REQUEST: "GetFeatureInfo",
                EXCEPTIONS: "application/vnd.ogc.se_xml",
                BBOX: map.getExtent().toBBOX(),
                X: event.xy.x,
                Y: event.xy.y,
                INFO_FORMAT: 'text/plain',
                QUERY_LAYERS: layerlist,
                FEATURE_COUNT: 1,
                WIDTH: map.size.w,
                HEIGHT: map.size.h},
                "http://server.org/cgi-bin/wmsmap?");

    OpenLayers.loadURL(url, '', this, setHTML);

    Event.stop(event);
}

NOTE:

prox is a layer defined elsewhere
mouseLoc is used later in setHTML()

It doesn't seem to matter which layer you use to call getFullRequestString() as long as it's a WMS type. Also, for this to return attributes (and not just the layer name and feature id) you have to add

"ows_include_items" "attribute1, attribute2, ..., attributeN"

or

"ows_include_items" "all"

to the metadata section of your WMS layer's map file entry. The way it works is that it will find all the features near (within a few pixels) of where you click and it will return up to FEATURE_COUNT records per query layer beginning with the nearest feature. So if you have two layers in QUERY_LAYERS and FEATURE_COUNT is set to 3, and you click on a spot where there are 5 records from layer 1 and 2 records from layer 2 that are all within range, this will return information from the nearest 3 in layer 1 and both from layer 2.

findLayerClick is triggered by a mouseclick and defined in init() like;

map.events.register('click', map, findLayerClick);

Now for the callback setHTML, that was referenced in the OpenLayers.loadURL() above, loads in plain text
(a xml version below)

/*
 * Get the Ajax response and pop up a info bubble
 */
function setHTML(response) {
    if (response.responseText.indexOf('no results') == -1) {
        var cat="Unknown", src="Unknown", leg="Unknown", linkinfo="";
        var lines = response.responseText.split('\n');
        for (lcv = 0; lcv < (lines.length); lcv++) {
            var vals = lines[lcv].replace(/^\s*/,'').replace(/\s*$/,'').replace(/ = /,"=").replace(/'/g,'').split('=');
            if (vals[1] == "") {
                vals[1] = "Unknown";
            }
            if (vals[0].indexOf('CATEGORY') != -1 ) {
                cat = vals[1];
            } else if (vals[0].indexOf('SOURCE') != -1 ) {
                src = vals[1];
            } else if (vals[0].indexOf('LEGEND') != -1 ) {
                leg = vals[1];
            } else if (vals[0].indexOf('DATAITEM') != -1 ) {
                linkinfo = vals[1];
            }
        }
        var popup_info = "<font size=2><b>" + cat +
                        "<br>Description:</b> " + leg +
                        "<br><a href='" + linkinfo + "' target='_blank'>More Info</a>" +
                        "<br><font size=1>Source: " + src +
                        "</font></font>";
        if (popup != null) {
            popup.destroy();
            popup = null;
        }
        popup = new OpenLayers.Popup.AnchoredBubble("SDVegetationInfo",
                                        mouseLoc,
                                        new OpenLayers.Size(250,120),
                                        popup_info,
                                        null,
                                        true);
        popup.setBackgroundColor("#bcd2ee");
//      popup.setOpacity(.7);
        map.addPopup(popup);
        popup.events.register("click", map, popupDestroy);
    }
}

If you're new to this and just trying to figure out what gets passed back, you should note that the code is application-specific, and has nothing to do with the getFeatureInfo process in general. So if you just want to see what gets returned, you can write setHTML() like this:

function setHTML(response) {
    alert(response.responseText);
}

xml version of setHTML

function setHTML(response) {
    var popup_info = "";

var doce = response.responseXML.documentElement;
var PCode = doce.getElementsByTagName('PCode')[0].firstChild.data;
var SCode = doce.getElementsByTagName('SCode')[0].firstChild.data;
        popup_info = "<font size=2><b>Project: </b>" + PCode +
                "<br>System Code: " + SCode + "</font>";

        if (popup != null) {
            popup.destroy();
            popup = null;
        }
        popup = new OpenLayers.Popup.AnchoredBubble("SDVegetationInfo",
                                        mouseLoc,
                                        new OpenLayers.Size(250,120),
                                        popup_info,
                                        null,
                                        true);
        popup.setBackgroundColor("#bcd2ee");
//      popup.setOpacity(.7);
        map.addPopup(popup);
        popup.events.register("click", map, popupDestroy);
    }

}

NOTE: popup is global var

And lastly the function popupDestroy

/*
 * Destroy popup and stop event
 */
function popupDestroy(e) {
    popup.destroy();
    popup = null;
    OpenLayers.Util.safeStopPropagation(e);
}

submitted by bwoodall

Last modified 9 days ago Last modified on May 19, 2016 11:53:57 PM