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", { });
etc
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();
Best Answer
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.
The closing () are for automatic loading of the function, which may or not be needed depending on your use.