Monday, May 20, 2024
51
rated 0 times [  57] [ 6]  / answers: 1 / hits: 39005  / 15 Years ago, tue, march 9, 2010, 12:00:00

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!


More From » dynamic-variables

 Answers
66

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.


[#97382] Friday, March 5, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marib

Total Points: 596
Total Questions: 120
Total Answers: 95

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;