javascript - Google Maps API v3 : Passing values to Listener function(), so as to make a circle when the marker is clicked? -


i want form circle around marker when marker clicked !

so, listener added marker , function needs act on circle.

here 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] undefined             } 

error: circle[j] undefined ?? (on event.addlistener line !)

why.. should defined there ?

how right way ? please !!

you have closure problem j. when function called, j reference last value j had in loop. so, j lat.length larger size of circle. solution force j evaluated when generating callback function:

function make_callback(circle, map) {     return function() {         circle.setmap(map);     }; } 

and then, in loop:

google.maps.event.addlistener(marker[j], 'click', make_callback(circle[j], map)); 

wrapping callback generation in separate function give value of circle[j] @ instant when call make_callback rather value when callback called.

j reference value, value points @ depends on when ask j value is. when bind function this:

google.maps.event.addlistener(marker[j], 'click', function() { something(j); }); 

the anonymous function doesn't ask j value until function called, function remembers going use j. when callback function executing, ask j current value , use that. means 2 things:

  • all callbacks bound in loop use same value of j.
  • j lat.length that's last value j assigned during loop.

by using make_callback function build callbacks, we're asking j value @ time we're binding callback. standard trick force j evaluated when has value want.


Comments