1

My question should be fairly straightforward.

If it helps to explain, I am currently using a javascript library called Leaflet. This library allows me to create a customizable online map that I can add markers to, which is what I am doing right here:

var iconId = null;

for (var i=1;i<4;i++)
{ 
  iconId = "mapMarker" + i; // L.marker does not accept this because it is a string and not an object
  var marker = L.marker([boulder.latitude, boulder.longitude], {icon: iconId}).addTo(map);
}

In another JS file, I have created 3 mapMarker objects with attributes compliant to Leaflet's documentation.

var mapMarker1 = L.icon({
    iconUrl: 'img/mapMarker1.png'
});
var mapMarker2 = L.icon({
    iconUrl: 'img/mapMarker1.png'
});
var mapMarker3 = L.icon({
    iconUrl: 'img/mapMarker1.png'
});

As you can see, I currently have a loop that creates a string with the name of the object I want to pass into the icon parameter, but the icon parameter is expecting an object, and not a string. Is there a way I can dynamically create object names and put them in "iconId"? I do not want to put this into a switch case, as it would be too large for my taste.

Thanks!

Omegalen
  • 1,456
  • 1
  • 13
  • 18
  • possible duplicate of [How to dynamically generate variables in JavaScript?](http://stackoverflow.com/q/18153999/), [How to “generate” unique variables?](http://stackoverflow.com/q/15894755/), [How to create dynamic variables in Javascript?](http://stackoverflow.com/q/21198725/) – outis Feb 11 '14 at 07:48
  • ... [Javascript dynamic variable name](http://stackoverflow.com/q/5117127/), [How to find JavaScript variable by its name](http://stackoverflow.com/q/724857/) – outis Feb 11 '14 at 07:55

1 Answers1

1

Whenever you find yourself creating a series of variables with similar names and incrementing numbers in the names, you should instead use the feature in JavaScript that's designed for this very purpose: an array.

Create an array of your map markers instead of the numbered variables:

var mapMarkers = [
    L.icon({
        iconUrl: 'img/mapMarker1.png'
    }),
    L.icon({
        iconUrl: 'img/mapMarker1.png'
    }),
    L.icon({
        iconUrl: 'img/mapMarker1.png'
    })
];

Now simply iterate through that array:

for( var i = 0;  i < mapMarkers.length;  i++ ) { 
    var marker = L.marker(
        [ boulder.latitude, boulder.longitude ],
        { icon: mapMarkers[i] }
    ).addTo( map );
}
Michael Geary
  • 28,450
  • 9
  • 65
  • 75
  • Excellent Mike! Could you explain how to use a for loop to create the mapMarkers array? I've been trying, but I'm a little confused about the syntax. – Omegalen Feb 11 '14 at 20:51