Search code examples
javascriptopenlayers

Not able to pass layer name as variable in openlayers


I am trying to load a layer from geoserver in Openlayers2.12 like this:

var layerName = 'something';
wms_layer_larisa2 =  new OpenLayers.Layer.WMS( layerName,"http://localhost:8080/geoserver/gwc/service/wms",  //http://192.168.2.6:8080/geoserver/wms
            {
                layers: "'es:"+layerName+"'",
                format:  "image/png",
                transparent: true,
                "version": "1.1.1",
                tiled: true

            },
            {
                format: "image/png",
                //STYLES: "pointOikismoi",
                //visibility: true, 
                //tileOptions: {maxGetUrlLength: 2048},
                displayOutsideMaxExtent: false,
                projection: new OpenLayers.Projection("EPSG:900913"),
            }
        );

        map.addLayer(wms_layer_larisa2);    

As you can see I don't define the name of the layer directly (as usually) but I want to pass it as a variable. This cause a failure in creating successfully the layer. Although its added in the layer switcher its not visible (everything gets pink so I guess it can not find it). Can you please tell me how to fix it? How should the following part look like:

layers: "'esoteriko:"+layerName+"'",

Solution

  • It doesn't work cause 'esoteriko' is a string. You could eval(), but i wouldn't recommend. It's the wrong use of it. Check e.g. http://24ways.org/2005/dont-be-eval/ for solutions or you do something with

    switch(string) {
      case 'esoteriko': 
      map.addLayer(esoterikolayer);
    break;
    ... other cases
    }