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, 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. jwill belat.lengthas that's the last value thatjwas 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.
来源:https://stackoverflow.com/questions/5838868/google-maps-api-v3-passing-values-to-listener-function-so-as-to-make-a-circ