Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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.

share|improve this answer

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.