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
    }); 
}
1

3 Answers 3

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

4
  • Your answer is constructing an array. But I also have to loop through it to actually have these markers appear in gmaps, right? Mar 31, 2014 at 19:42
  • @FrankKluytmans Due to retrieve information from array Yes, you have to make another loop for it
    – nanobash
    Mar 31, 2014 at 19:43
  • @FrankKluytmans: I recommend to read the MDN JavaScript Guide about arrays to learn how to work with them. Mar 31, 2014 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... Mar 31, 2014 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";
}
0

Maybe you can put all maker in an Object.

var myObject = [];   
myObject.push(marker);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.