[GIS] Query WMS for available layers using Openlayers

openlayers-2wms

Is it possible to use Openlayers to return an array of available Layers on a WMS?

I am attempting to allow users to add a layer.wms to a map. I would like to allow the user to view available layers, select those layers that they want, and then pass that arrary to layer.wms params, add the layer and redraw.

Just wondering if there was a simple way to query layers available from a WMS.

Best Answer

Yes it is possible. You can make GetCapabilities request to WMS server, parse result with OpenLayers.Format.WMSCapabilities(), and you'll get list of layers and lot of other useful information.

UPDATE: here is sample code. I suggest, that you console.log() response and examine it with some developer tool (like FireBug). It's easy to find list of layers.

NB! This is GET query and, because of same origin policy, you need to set up proxyhost to get it work.

var wmsCapabilitiesFormat = new OpenLayers.Format.WMSCapabilities();
var onLayerLoadError = function() { /* Display error message, etc */ }

...

OpenLayers.Request.GET({
    url : yourWMSUrl,
    params : {
        SERVICE: 'WMS',
        VERSION: yourWMSVersion, // For example, '1.1.1'
        REQUEST: 'GetCapabilities'
    },
    success: function(r){

        var doc = r.responseXML;
        if (!doc || !doc.documentElement) {
            doc = r.responseText;
        }

        var c = wmsCapabilitiesFormat.read(doc);
        if (!c || !c.capability) {
            onLayerLoadError();
            return;
        }       

        // Here is result, do whatever you want with it
        console.log(c);

    },
    failure : function(r) {
        onLayerLoadError();
    }
});