0

I started using the Leaflet library. I am trying to add an event when clicking on a marker.

I have a loop that creates markers on the map based on the amount of data in the DB. It turns out this file:

array(6) {
  [0]=>
  array(13) {
    [0]=>
    string(9) "37.162047"
    [1]=>
    string(10) "140.328209"
    [2]=>
    string(321) "Japan word word word word word word word word word word word word word word word"
    [3]=>
    string(12) "Japan"
    [4]=>
    NULL
    [5]=>
    string(10) "Tokyo"
    [6]=>
    string(10) "Ocean"
    [7]=>
    string(10) "12.04.2013"
    [8]=>
    string(1) "5"
    [9]=>
    string(1) "8"
    [10]=>
    string(3) "345"
    [11]=>
    string(6) "676796"
    [12]=>
    string(7) "6799654"
  }
  [1]=>
  array(13) {
    [0]=>
    string(9) "49.775444"
    [1]=>
    string(9) "10.757696"
    [2]=>
    string(325) "Germany  word word word word word word word word word word word word word word word"
    [3]=>
    string(16) "Germany"
    [4]=>
    NULL
    [5]=>
    string(12) "Berlin"
    [6]=>
    string(10) "Rock"
    [7]=>
    string(10) "21.03.2010"
    [8]=>
    string(1) "6"
    [9]=>
    string(1) "4"
    [10]=>
    string(5) "45736"
    [11]=>
    string(7) "7699870"
    [12]=>
    string(7) "4563463"
  }
..............
}

This file is obtained using this code:

$data_encode = (json_encode($data));

Parsed using this:

var map_data = JSON.parse('<? echo $data_encode; ?>');

Markers JS code:

function description_event(e) {
    dscr.innerHTML = map_data[i][2];
}
for (var i = 0; i < map_data.length; i++) {
    marker = new L.marker([map_data[i][0], map_data[i][1]])
    .bindPopup("<b>" + map_data[i][8] + "</b>" + "<br>" + map_data[i][7] + "<br>" + map_data[i][3])
    .on('click', description_event)
    .addTo(map);
   }
}

I need to send data from a DB on a click on a marker. So that, for example, "Japan" is written on the marker and the description "Japan word word ..." is sent to the block, to the div with id = "dscr". But I can't do it. It sends on click only if map_data [0] [2]; and only "Japan word word ...", and map_data [i] [2]; does not work. That is, iteration does not work. I tried all the ways.

Same problem with this one

.on('click', function() { dscr.innerHTML = map_data[0][2]; })
  • Classic lack of closures. The variable `i` doesn't have the scope you would hope. See also https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – IvanSanchez Jun 15 '21 at 08:52

0 Answers0