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

Sign up to request clarification or add additional context in comments.

4 Comments

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

Comments

0

Maybe you can put all maker in an Object.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.