0

I'm working (with Django framwork) on a map with the leaflet library, I want to show some text in a div when I click on a marker.

I've made a JS function to create a div with some text in it:

function create_div(text):
{
    div = document.createElement(div);
    div.id = 'article';
    div.textContent = text;
    document.body.appendChild(div);
}

and then I call this function in the "on" methode given by leaflet because I want to call it when I click on a marker :

var articles = {{ list_json | safe }};
for (var i = 0; i < {{ nb_of_articles | safe }}; i++)
{
    var text = articles[i].fields.text; //I put the text of the i-th marker in text.
    var lat = articles[i].fields.lat;
    var lon = articles[i].fields.lon;
    var marker = L.circleMarker([lat,lon]);

    marker.on('click', function(e) {create_div(text);} );
    marker.addTo(mymap);
}

It kinda work but it puts the text of the last object in all the div associate with my marker.


For example if I have:

article[0].fields.text = "hello"
article[1].fields.text = "world"

I get "world" in the divs, regardless of the marker I click on.


I would like "hello" in the div when I click on the first marker, and "world" in the div when I click on the second marker.

Here is what it looks like after I click on any of the markers:

after I click

I hope I'm clear enough, please tell me if you need more information.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
koumoul
  • 13
  • 4
  • Classic JS scope issue. You should be able to find many resources on that topic, including here on SO. – ghybs May 09 '17 at 12:30
  • Pretty much a duplicate of https://stackoverflow.com/questions/35428801/leaflet-marker-event-fires-at-wrong-time – IvanSanchez May 09 '17 at 13:28
  • Possible duplicate of [Leaflet marker event fires at wrong time](http://stackoverflow.com/questions/35428801/leaflet-marker-event-fires-at-wrong-time) – IvanSanchez May 09 '17 at 13:28
  • Oh ok !! i'm new to JS and I've just discover this closure shit !! Thank you ! :) I will edit the post with my solution when I figure it out – koumoul May 09 '17 at 19:11

1 Answers1

1

Here we go for the saving solution : I use let for the declaration of text, it will solve the closure issue.

let text = articles[i].fields.text;

( What's the difference between using "let" and "var" to declare a variable? )

I hope this is a good solution :)

koumoul
  • 13
  • 4