4

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.

1 Answer 1

5

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();
    }
});
4
  • Thanks for the response. When I call the request.GET OL is sending the request with the OPTIONS method instead of the GET method, any ideas? Commented Apr 3, 2013 at 17:28
  • My intent is too allow users to define the WMS they are adding. That being said how would I allow for an unknown WMS to be added, assuming I do not want to change proxy.cgi to include the new remote server. This question may be out of scope of this, I will search SO also. Commented Apr 8, 2013 at 16:17
  • 1
    I haven't used lot of different proxys, usually it's not neccessary to define allowed remote servers in there. If proxy.cgi does require that - look for another proxy script. Beside that, there should be no problems to add user-defined WMS services dynamically. Commented Apr 8, 2013 at 18:21
  • Can you provide full code for me or else you can mail me to [email protected]
    – user28536
    Commented Jun 29, 2016 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.