Custom Request for WMS GetFeatureInfo in OpenLayers 2

getfeatureinfoopenlayers-2wms

In OpenLayers, there is a WMSGetFeatureInfo control that can be attached to a layer and listen to click or hover events on the map, requesting info on the feature being currently clicked (or pointed) at.

However, how to make a custom GetFeatureInfo request, with the following input?

  • layer
  • [x,y] mouse position OR [lon,lat] position in the map

Is it possible to do this elegantly with the WMSGetFeatureInfo control, or do I have to ajax the request myself?

Best Answer

The WMSGetFeatureInfo doesn't work by requesting info on the feature being currently clicked as such. It works by formulating a WMS GetFeatureInfo request which passes a BBOX string to the WMS server. So, when you click on the map the location coordinates are captured and then sent to a WMS server as the request. You could see this in action by using something like Fiddler2 to inspect the request being made.

It is possible to create this elegantly without resorting to Ajax as the control does not have to be associated to a specific layer at creation. You can set the layer on the beforegetfeatureinfo event. Something like this would work:

var queryableMapLayers = [];
var getFeatureControl = new OpenLayers.Control.WMSGetFeatureInfo({
  url: your_wms_url.here // Your WMS server url here,
  drillDown: false, // Or true if you want drill down (see the docs)
  hover: false, // Or true if you want but bear in mind this could get chatty
  layers: queryableMapLayers,
  eventListeners: {
    getfeatureinfo: function (event) {
      // Code here if you want to process the results
    },
    beforegetfeatureinfo: function(event) {
      // Code here to set the content of queryableMapLayers
      // The event object will contain xy of mouse click
    },
    nogetfeatureinfo: function(event) {
      // Code here if no queryable layers are found
    }
  } 
});

// Add the control to your map
map.addControl(getFeatureControl);

We use this approach in our applications along with a custom JSON response from GeoServer to emulate an ArcGIS style feature info dialog.