I’ve created a simple js project which plots a series of points using leaflet.js.
I then want to populate an info window with point specific data with an on click event. But I can’t seem to get it to work.
This is roughly what I’ve done:
var circle = L.circle(
[data[i]['latitude'], data[i]['longitude']],
50,
{ color: 'red', fillColor: 'red', fillOpacity: .5}
).addTo(map)
.bindPopup(data[i]['SCHNAME'])
.on('click', fill_info_window(data, i));
function fill_info_window(data, i){ /* fill data */ }
Unfortunately, it automatically fills the window with the latest data.
Why isn’t it working?
You can see the project here:
On this line:
…you’re calling the
fill_info_windowfunction, not just referring to it. You want to do something like this:unless you’re in a loop (that
ivariable makes me think maybe you are). If you are, then:…where
makeHandlerlooks like this:The reason you don’t want my first answer in a loop is that all of the handlers will refer to the same
dataandivariables, and see their value as of when the handler is called, not when it’s registered. That’s why we use themakeHandlerfunction instead, so it creates a closure over something that doesn’t change. More on my blog: Closures are not complicated