2

I am using Angular 5 and ngx leaflet including the marker cluster. Everything works fine but the click function always outputs the name of the last element of the list whereas the tooltip contains the correct name.

for (var i  of this.list) {
      var markerItem = L.marker([i.lat, i.lng], {icon})
        .bindTooltip('<h5>'+i.name+'</h5>')
        .on('click', () => {
          console.log(i);
          this.draw(i);
        });
      data.push(markerItem)
    }
    this.markerClusterData = data;
Tonerl
  • 23
  • 6

1 Answers1

3

You could change:

.on('click', () => {
  console.log(i);
  this.draw(i);
}

To:

.on('click', ((i) => () => {
  console.log(i);
})(i))

The solution above makes use of closures. You can read more about them here.

You can also change

for (var i  of this.list) {

to

for (let i  of this.list) {

This solution makes use of the let keyword.

Take a look at this JSBin to see a working example.

Iavor
  • 1,997
  • 16
  • 27
  • Not stupid at all; it's a tricky JS concept. Glad I could help :-) – Iavor Mar 19 '18 at 14:50
  • @Iavor you should at least mention the concept of closure, if possible explain a little bit or point to other resources (including here on SO). Give a poor man a fish, you feed him for a day. Teach him fishing, you feed him for the rest of his life. – ghybs Mar 19 '18 at 16:43
  • That's true @ghybs. I'll include some resources in my answer. – Iavor Mar 19 '18 at 16:59
  • 1
    @ghybs I added a bit more detail and some resources. Do you think I should add anything else? – Iavor Mar 19 '18 at 17:21