I am working in Google Maps and have three+ tile overlays to create. An example:
Tile Overlay
var parkingOptions = { //Parking Overlay
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tilesparking/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
};
var parkingMapType = new google.maps.ImageMapType(parkingOptions);
However, to avoid 404 errors by missing tiles outside of my mapping range, my code is a little more complex; thus, I intended to make a loop where a specific keyword assigned to each overlay (here given as “parking”) would be inserted into the above code. Thus:
For Loop
var tileNames = ["base", "parking", "access"];
for (var i = 0; i < tileNames.length; i++) {
//insert Tile Overlay code here
};
However, I have one particular issue: I can not find a way to take the string from the tileNames array and use them in initializing the two variables in the Tile Overlay code. Ideally, I would like to achieve something like this:
Attempt 1
var tileNames[1] + "Options" = { //ideally: var parkingOptions = {
//insert remaining code
};
However this doesn’t work, nor did I really expect it to. Neither would trying to create those full strings and trying to insert it into the initialization:
Attempt 2
var newOptions = tileNames[1] + "Options";
var newOptions = {
//insert remaining code
};
Thus, is there a way to do place a string into initializing variables?
Note: I have included my own alternative solution to the problem as an answer. It should work, but it destroys the names of the variables and replaces it with a nondescript array variable. I preferably would like to retain a descriptive variable name as they are used often in adding and hiding the overlays in the resulting code.
Solution For this question anyways…
var tileNames = ["beloit", "parking", "access"];
var mapType = {};
for (var i = 0; i < tileNames.length; i++) {
var tileOptions = {
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tiles" + tileNames[i] + "/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
};
mapType[tileNames[i]] = new google.maps.ImageMapType(tileOptions);
};
The other part of the puzzle, the “tileNames[i]” in the getTileUrl function is undefined because the function wants it when it is executed rather than placing the name string into the function; however, that is a new question to be found here: Javascript: Making a variable static when defining a function in a loop?
you can’t do this:
but you can do this:
or if you are in a function
EDIT: