views:

153

answers:

4

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!

+4  A: 

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.

Plynx
Thanks Plynx! This ended up working fine for me. I appreciate the help.
julio
@julio, Plynx: Not sure how to say this without sounding bitter, but this would be terrible javascript. Like I said in my answer, this very thing is what javascript arrays are for. If you're happy to write your javascript like this then fair enough but I think it would make you a better coder if you learned to do it the correct way :-)
Andy E
+3  A: 

You'd be better off creating a javascript object which you can use somewhat like an associative array is used in PHP:

var types = ['hospital','church','library','store'];
var landmarks= {};
for (var i in types) {
    landmarks[types[i]]= new google.maps.Icon();
    landmarks[types[i]].image = "icon" + i + ".png";
} 
alert(landmarks['hospital'].image);  // displays "icon0.png"
pygorex1
+2  A: 

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:

var myObj =           // object version
{
   "item0": "blah",
   "item1": "blah"
   // etc
}
var myArr =           // array version
[
   "blah",
   "blah"
   // etc
]

Much more sensible to use the array:

landmarks = []; // new array
types = array('hospital','church','library','store',etc);  
var i=0;  
while (i<=types.length) {  
    landmarks.push(new google.maps.Icon());
    landmarks[i].image = "icon" + i + ".png";
    i++;  
}

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:

var myCustomVar = "landmark" + i;
window[myCustomVar] = new google.maps.Icon();

alert(landmark0);

But this would be polluting the global namespace with many unnecessary variables. So you'd still be better with an array:

window.landmarks = [];
landmarks.push(new google.maps.Icon());
// etc...
Andy E
thanks Andy-- I tried your solution, and it appears that you can't push this object onto an array. I got a syntax error every time I tried. However, when I did it like this:var icon = new google.maps.Icon();landmarks.push(icon);it worked fine. the problem then became that I'd get a "landmark[i] undefined" if I tried to set the other attributes usinglandmarks[i].image = etc.Any thoughts?
julio
@julio: take a look at the push method docs on MSDN - http://msdn.microsoft.com/en-us/library/6d0cbb1w(VS.85).aspx. Make sure your `landmarks = []` is outside of the loop, too, otherwise you're constantly overwriting it. Trust me, what you're trying to achieve is the reason arrays exist.
Andy E
ps - the push method very usefully returns the new length of the array, so you could check the returned value to see if what you're pushing is making it into the array.
Andy E
+1  A: 

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:

> window["myNamedVar"] = "Hello, World!";
> console.log(myNamedVar);
  "Hello, World!"
Felix