Search code examples
angularleafletleaflet.markerclusterngx-leaflet

Leaflet marker click always shows last element


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;

Solution

  • 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.