0

I'm trying to make a loop in which I create multiple markers for Google Maps. I want these markers to be named marker+int. I can't merge 2 variable names as I found out, so I need another way to do this. Can anyone help me out? I don't have an array to loop through...

var counter = 0;

for (var i = 0; i < localStorage.length; i++){
    counter++;
    var marker = new google.maps.Marker({
        position: myLatlng, 
        map: map,
        icon: image,
        shadow: shadow,
        title: label
    }); 
}
annemartijn
  • 1,538
  • 1
  • 23
  • 45
Frank Kluytmans
  • 533
  • 2
  • 10
  • 25
  • possible duplicate of [JavaScript: Dynamically Creating Variables for Loops](http://stackoverflow.com/questions/6645067/javascript-dynamically-creating-variables-for-loops) – Felix Kling Mar 31 '14 at 19:44

3 Answers3

3

What about to define array and iterate though it like:

var marker = [];

for ( var i = 0; i < localStorage.length; i++ ) {
    marker[i] = new google.maps.Marker({
        position: myLatlng, 
        map: map,
        icon: image,
        shadow: shadow,
        title: label
    }); 
}

You can output result from marker array simple just like

for ( var j = 0; j < marker.length; j++ ) { // output all the information from marker array
    console.log(marker[j].position);
    console.log(marker[j].map);
    console.log(marker[j].icon);
    console.log(marker[j].shadow);
    console.log(marker[j].title);
}

NOTE: counter variable isn't needed as you already have counter which is represented by i variable inside the loop

nanobash
  • 5,419
  • 7
  • 38
  • 56
  • Your answer is constructing an array. But I also have to loop through it to actually have these markers appear in gmaps, right? – Frank Kluytmans Mar 31 '14 at 19:42
  • @FrankKluytmans Due to retrieve information from array Yes, you have to make another loop for it – nanobash Mar 31 '14 at 19:43
  • @FrankKluytmans: I recommend to read the [MDN JavaScript Guide about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object) to learn how to work with them. – Felix Kling Mar 31 '14 at 19:54
  • I understand arrays quite well I think. Looping is not the problem. But how do I output all the markers in the loop? I don't want to log them but actually have them shown on the map... – Frank Kluytmans Mar 31 '14 at 20:00
0

You an object or an array

var markers = [];
for (var i=0; i<10; i++) {
    markers[i] = "Hello";
}

If you want to have names, than use an object

var obj = {};
for (var i=0; i<10; i++) {
    obj["marker" + i] = "Hello";
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Maybe you can put all maker in an Object.

var myObject = [];   
myObject.push(marker);
nanobash
  • 5,419
  • 7
  • 38
  • 56
system7
  • 130
  • 1
  • 8