1

How do I 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) returns the whole array:

enter image description here

When I change to console.log(data[i]); I get undefined message:

enter image description here

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

Only for marker.bindpopup this working fine, but for on click it's not working.

enter image description here

1

1 Answer 1

2

You could achieve what you want by adding custom property myID (could be any name) to marker and setting it to index value i. In this way the correct index to data array will be available at click event.

Something like 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);
}
1
  • thank you very much, you saved my day.
    – AdityaDees
    Commented May 6, 2019 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.