I want to form a circle around the marker when the marker is clicked!
So, Listener is added to marker and the function needs to act on the circle.
Here is my Code :
for(var j=0;j<lat.length;j++)
{
var pos = new google.maps.LatLng(lat[j],lng[j]);
var marker_options = {position: pos, map:map, draggable:false};
marker[j] = new google.maps.Marker(marker_options);
circle_option = {strokeColor:"#FF0000",strokeOpacity:0.8,strokeWeight:2,fillColor:"#FF0000",fillOpacity:0.35,map:null,center:pos,radius:500};
circle[j] = new google.maps.Circle(circle_option);
google.maps.event.addListener(marker[j], 'click', function() {circle[j].setMap(map);}); // Error : circle[j] is undefined
}
Error: circle[j] is undefined ?? (On the event.addListener line !)
Why.. it should be defined there ?
How to do this is the right way ? Please help!
You have a closure problem with
j. When your function is called,jwill reference the last value thatjhad in the for loop. So,jwill belat.lengthwhich is larger than the size ofcircle. The solution is to forcejto be evaluated when generating the callback function:and then, in your loop:
Wrapping the callback generation in a separate function will give you the value of
circle[j]at the instant when you callmake_callbackrather than the value when the callback is called.jis a reference to a value, the value that it points at depends on when you askjwhat its value is. When you bind a function like this:The anonymous function doesn’t ask
jwhat its value is until the function is called, the function simply remembers that it is going to usej. When the callback function is executing, it will askjfor its current value and use that. This means two things:j.jwill belat.lengthas that’s the last value thatjwas assigned during the loop.By using the
make_callbackfunction to build the callbacks, we’re askingjfor its value at the time that we’re binding the callback. This is just a standard trick to forcejto be evaluated when it has the value we want.