Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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

Your Answer

 
discard

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.