Google Maps Api V3 : Passing Values To Listener Function(), So As To Make A Circle When The Marker Is Clicked?
Solution 1:
You have a closure problem with j
. When your function is called, j
will reference the last value that j
had in the for loop. So, j
will be lat.length
which is larger than the size of circle
. The solution is to force j
to be evaluated when generating the callback function:
function make_callback(circle, map) {
return function() {
circle.setMap(map);
};
}
and then, in your loop:
google.maps.event.addListener(marker[j], 'click', make_callback(circle[j], map));
Wrapping the callback generation in a separate function will give you the value of circle[j]
at the instant when you call make_callback
rather than the value when the callback is called.
j
is a reference to a value, the value that it points at depends on when you ask j
what its value is. When you bind a function like this:
google.maps.event.addListener(marker[j], 'click', function() { something(j); });
The anonymous function doesn't ask j
what its value is until the function is called, the function simply remembers that it is going to use j
. When the callback function is executing, it will ask j
for its current value and use that. This means two things:
- All the callbacks that you bound in that loop will use the same value of
j
. j
will belat.length
as that's the last value thatj
was assigned during the loop.
By using the make_callback
function to build the callbacks, we're asking j
for its value at the time that we're binding the callback. This is just a standard trick to force j
to be evaluated when it has the value we want.
Post a Comment for "Google Maps Api V3 : Passing Values To Listener Function(), So As To Make A Circle When The Marker Is Clicked?"