[GIS] Change marker icon on click using leaflet

leafletmarkers

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) {
  testmarker.setIcon(selectedIcon);
});

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) {
  marker.setIcon(selectedIcon);
});

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 this.map.on 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?

Best Answer

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) {
        e.target.setIcon(selectedIcon);
        document.getElementById('someDiv').innerHTML = points[e.target.options.id][2];
}); 
}