Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have a closure problem with <code>j</code>. When your function is called, <code>j</code> will reference the last value that <code>j</code> had in the for loop. So, <code>j</code> will be <code>lat.length</code> which is larger than the size of <code>circle</code>. The solution is to force <code>j</code> to be evaluated when generating the callback function:</p> <pre><code>function make_callback(circle, map) { return function() { circle.setMap(map); }; } </code></pre> <p>and then, in your loop:</p> <pre><code>google.maps.event.addListener(marker[j], 'click', make_callback(circle[j], map)); </code></pre> <p>Wrapping the callback generation in a separate function will give you the value of <code>circle[j]</code> at the instant when you call <code>make_callback</code> rather than the value when the callback is called.</p> <p><code>j</code> is a reference to a value, the value that it points at depends on when you ask <code>j</code> what its value is. When you bind a function like this:</p> <pre><code>google.maps.event.addListener(marker[j], 'click', function() { something(j); }); </code></pre> <p>The anonymous function doesn't ask <code>j</code> what its value is until the function is called, the function simply remembers that it is going to use <code>j</code>. When the callback function is executing, it will ask <code>j</code> for its current value and use that. This means two things:</p> <ul> <li>All the callbacks that you bound in that loop will use the same value of <code>j</code>.</li> <li><code>j</code> will be <code>lat.length</code> as that's the last value that <code>j</code> was assigned during the loop.</li> </ul> <p>By using the <code>make_callback</code> function to build the callbacks, we're asking <code>j</code> for its value at the time that we're binding the callback. This is just a standard trick to force <code>j</code> to be evaluated when it has the value we want.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload