Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a map with many (>100) markers on it. I would like to make it so that clicking on these changes the icon to a highlighted version. I've created two custom icons, one regular, and one highlighted. I've gotten this to work with single markers, but can't find any way to set it up so each icon can be changed by clicking on it.

Here is working code for one icon:

var testmarker = L.marker([44.0, -73.0], {icon: unselectedIcon});

testmarker.on('click', function(e) {

However I have many markers and use a for loop to place them:

//points is a 2 dim array with lat/long pairs
for (i = 0; i <= points.length-1; i++) {
    var marker = L.marker([points[i][0], points[i][1]], {icon: unselectedIcon});    

marker.on('click', function(e) {

I tried giving each marker a unique variable name by using an array:

for (i = 0; i <= points.length-1; i++) {
    testmarker[i] = L.marker([points[i][0], points[i][1]], {icon: unselectedIcon}); 
    testmarker[i].on('click', function(e) {
alert(e.latlng); e.setIcon(selectedIcon); 

Which just gives me "undefined" in the alert.

Changing testmarker[i].on to only gives an alert on clicking the map (no icon change).

Changing that entire line to:

testmarker[i].on('click', function(e) {
alert(e.latlng); testmarker[i].setIcon(selectedIcon);

Changes the last one (when any is clicked), while also giving an undefined alert.

How can I set the markers up so that each can individually be changed with a click, but without using hundreds of repeated code blocks for each one?

share|improve this question
up vote 7 down vote accepted

I ended up solving this. I also figured out you can add arbitrary options and access them later. That is useful for assigning unique ids to markers:

for (i = 0; i <= points.length-1; i++) {
    testmarker[i] = L.marker([points[i][0], points[i][1]], {icon: unselectedIcon, id: i}); 
    testmarker[i].on('click', function(e) {;
        document.getElementById('someDiv').innerHTML = points[][2];
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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