I've built a data-driven google map with different icons that get assigned to the map depending on the type of item located. So if I have 5 types of landmark, and each gets a different icon (store, library, hospital, etc.)-- what I'd like to do is generate the google icon objects dynamically. I was thinking something like this:
types = array('hospital','church','library','store',etc);
var i=0;
while (i<=types.length) {
var landmark + i = new google.maps.Icon();
landmark.image = "icon" + i + ".png";
i++;
}
however, as you've probably guessed, this doesn't work. I also tried using eval, like this:
while (i<=types.length) {
doIcon(i);
i++;
}
function doIcon(i){
eval("var landmark" + i + " = new.google.maps.Icon();");
return eval("landmark" + i);
}
but it didn't work either-- I'd appreciate any pointers on generating javascript variables dynamically. It's got to be pure js, I could do it in PHP but that's not an option here.
Thanks!
You'd be better off creating a javascript object which you can use somewhat like an associative array is used in PHP:
Just to answer your question directly (although please note that this is not the solution you want. Check out the other answers. This is just for documentation!), here's a copy-paste from a JavaScript console:
If you're going to do it using a declared object such as
Landmark["landmark" + i]
, you really may as well use an index array rather than an associative, it's much easier for iteration. Objects aren't really used with indexed properties because Arrays do a much better job of it:Much more sensible to use the array:
It makes more sense to do it that way and
for...in
loops on objects can get a bit messy with prototyped properties being enumerable, etc.If you're trying to make a variable global, add it to the window object:
But this would be polluting the global namespace with many unnecessary variables. So you'd still be better with an array:
It's really easy to do:
object["variablename"] = whatever;
So for example you could have an object:
var Landmarks = {}
and you could add to it like so:Landmarks["landmark" + i] = new google.maps.Icon();
and pass it that way.If you need these variables to be global (why would you?) you can access the global object directly using
window
.Do you really need those variables? Can't you do with this:
Modifications done based on comment:
icon name pattern changed from icon + index + .png to icon + type + .png and saving the results of the loop.
the result is : { hospital : icon, church : icon, ... }
where icon is a google map icon that has an image attribute that is a string of the form "icon{type}.png" , e.g, iconhostpital.png, iconchurch.png.
To use the icons write
landmarks.type
where type is one the names in the array of types, e.g.landmarks.hospital
.if the image names are of the form icon + number + .png, and the number for each type is equivalent to its index in the array replace the call createIcon(type[i]) for createIcon(i).