javascript - google maps multiple markers clickevent -
im looping , placing markers, when click marker, respond same value
here code
for(a=0; < prod.length; a++){ // add marker map var mylatlng = new google.maps.latlng(prod[a]['lat'],prod[a]['lon']); var marker = new google.maps.marker({ position: mylatlng, map: map, title: prod[a]['name']+" \n"+prod[a]['description'], icon: image }); google.maps.event.addlistener(marker, "click", function() { show_details(a); }); }
function show_details, has same value
i have looked @ other answers here didnt solve problem.
tipical problem in async programming/scripting. a
variable passing, when click event runs, , value of after for
loop finishes. should create inner function scope, , save value of a
in variable, lives in scope. solution:
(function(z){ google.maps.event.addlistener(marker, "click", function() { show_details(z); }); })(a);
the a
variable lives outside callback function too. if modify value of a
( or for
loop modify that) , when event handler called, see modified a
.
help link: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ .
Comments
Post a Comment