I have a lot of OpenLayers layers that change every day so instead of having to create, and change a long list of these:

var layerone = new OpenLayers.Layer.XYZ("mylayer1", "mylayer1/${z}/${x}/${y}.png", { });

var layercool = new OpenLayers.Layer.XYZ("mylayer1", "mylayer1/${z}/${x}/${y}.png", { });


I'd like to first make an array of layer names:

var mylayers = new Array("layerone","layercool","layeryo","layerhello");

and then create all these layers in a for loop, something like this:

var length = mylayers.length;
for (var i = 0; i < length; i++) {

mylayers[i] = new OpenLayers.Layer.XYZ("mylayers[i]", "mylayers[i]/${z}/${x}/${y}.png", { }); 


How do I first of all create unique var names for each layer in the foor loop and then do the loop? I read somewhere to use window[layers[i]] = new OpenLayers.Layer... or maybe eval? but I'm not sure how to access these later on when doing the map.addLayers();

2 Answers 2


An update using OpenLayers 3.

In this example, data is first parsed from an external php file (foo.php) using $.getJSON, placed into an array of objects, and added to the map through $.each iterations. Example shown is for a kml file, but can be adapted for any ol.Layer construct.

(function get_layers() {
        function(data) {
            var jsArray = (data);  
            $.each(jsArray, function(key, value) {
                var layer = value.baz;  //baz as a value in the array 
                var url = value.buz;  //buz as a value in the array 
                var layer = new ol.layer.Vector({
                    source: new ol.source.Vector({
                      url: url,
                      format: new ol.format.KML(),

The closing () are for automatic loading of the function, which may or not be needed depending on your use.


you can get your added layers by map.getLayersByName('layerone'). and you can give layerId to your layer so you can get them all.

for (var i = 0; i < length; i++) {
mylayers[i] = new OpenLayers.Layer.XYZ(mylayers[i], mylayers[i] + "/${z}/${x}/${y}.png", {
              layerId : i



i hope it helps you...

  • Yes! Works like a charm. I was close with my own code but not all the way. Thanks!
    – oskarlin
    Jan 15, 2013 at 16:16

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.