0

the problem I have is I can't get the data according to the marker I clicked on.

for(i in data) {
    var title = data[i].title,
    id = data[i].id,      
    position = data[i].position,      
    kriteria = data[i].data.kriteria,     
    iconUrl =  data[i].icon.url,
    pa_judul = data[i].data.pa_judul,
    marker = new L.Marker(new L.latLng(position), 
    {

        icon:  L.icon({
            iconUrl:   iconUrl,
        })

    }, 
    {title: title},

    ).addTo(map);

    marker.bindPopup('ID: '+ id ).on('click', function(e) {
        console.log(data);
        $('#ModalDetail').modal('show').on('shown.bs.modal', function(e) {
        });
    });
    markersLayer.addLayer(marker);
}

console.log(data) return all array enter image description here

but when i change to console.log(data[i]); i got undefined message enter image description here

and if i change to console.log(data[0]) or data[1] and data[2] the results is not error and i can get the data

enter image description here

if only for marker.bindpopup this working fine, but for onclick is not working. enter image description here

can you help me? i just need get data from clicked marker.

AdityaDees
  • 1,022
  • 18
  • 39
  • 1
    See example 6 of https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – ghybs May 06 '19 at 02:57

1 Answers1

0

try too use this

for(i in data) {
    var title = data[i].title,
    id = data[i].id,      
    position = data[i].position,      
    kriteria = data[i].data.kriteria,     
    iconUrl =  data[i].icon.url,
    pa_judul = data[i].data.pa_judul;

    var marker = new L.Marker(new L.latLng(position), 
    {
      icon: L.icon({
        iconUrl: iconUrl,
      }),
      title: title
    }
    ).addTo(map);
    marker.myID = i;

    marker.bindPopup('ID: '+ id ).on('click', function(e) {
      var i = e.target.myID;
      console.log(data[i]);
      $('#ModalDetail').modal('show').on('shown.bs.modal', function(e) {
      });
    });
    markersLayer.addLayer(marker);
}