Picking a Feature’s Attribute Value From a WMS Layer With OpenLayers

There are many nice examples out there of how to use a getFeatureInfo request in OpenLayers to display a feature’s attribute table. In some applications it can be useful though not to display the full attribute table but to only select one attribute value from it and output it somewhere, e.g. in a text field.

This post describes how to pick the road id from a road wms layer and write the id value into a text input field.

OpenLayers offers a convenient class to achieve this: OpenLayers.Control.WMSGetFeatureInfo.

Let’s create an object of this class, register and activate it:

roadidPicker = new OpenLayers.Control.WMSGetFeatureInfo({
                url: 'http://localhost:8080/geoserver/wms', 
                title: 'identify features on click',
                layers: [wms],
                queryVisible: true
roadidPicker.infoFormat = 'application/vnd.ogc.gml';
roadidPicker.events.register("getfeatureinfo", this, pickRoadid);

Now, every time the user clicks onto the map, a getFeatureInfo request is issued and the function pickRoadid() is called. In pickRoadid(), we’ll define which value we want to pick from the feature. The ‘id’ of the feature will be written into a text input field called ‘roadId’:

function pickRoadid(e) {
  if (e.features && e.features.length) {
     var val = e.features[0].attributes.id;
     document.getElementById('roadId').value = val;

You might have noticed the ‘[0]’. That’s because the click event comes with a list of features within the reach of the mouse click. For my application, I can only use one value and the first feature in this list is as good as any.

  1. Ashis said:

    I have Geoserver and Apache server are in different locations, and I have no physical access to the Apache server. Is there any ways to show my maps via Apache.

    I guess I need to setup or write some proxy.

  2. Mark said:

    Great example, just what I was looking for. Thank you very much.

  3. Boedy said:


    Could you give me an example how to accomplish the same effect when using the WFS protocol instead of the WMS protocol?

  4. Ann said:


    I try to do the example, but it doesn’t work, can show html example?


%d bloggers like this: