Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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();

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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...

share|improve this answer
Yes! Works like a charm. I was close with my own code but not all the way. Thanks! –  Oskar Karlin Jan 15 '13 at 16:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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