admin管理员组文章数量:1356591
Im looping and placing some markers, but when i click a marker, they all respond with the same value
Here is my code
for(a=0; a < prod.length; a++){
// we add marker to 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, a always has the same value
I have looked at the other answers here but that didnt solve my problem.
Im looping and placing some markers, but when i click a marker, they all respond with the same value
Here is my code
for(a=0; a < prod.length; a++){
// we add marker to 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, a always has the same value
I have looked at the other answers here but that didnt solve my problem.
Share Improve this question edited Dec 7, 2013 at 20:21 Kara 6,22616 gold badges53 silver badges58 bronze badges asked Apr 5, 2013 at 13:15 GrumpyGrumpy 2,2531 gold badge26 silver badges40 bronze badges1 Answer
Reset to default 10Tipical problem in async programming/scripting. The a
variable passing, when the click event runs, so , the value of that is what is after the for
loop finishes.
You should create an inner function scope, and save the value of a
in a variable, what lives only in that scope.
The solution:
(function(z){
google.maps.event.addListener(marker, "click", function() {
show_details(z);
});
})(a);
The a
variable lives outside the callback function too. So if you modify the value of a
( or the for
loop modify that) and when the event handler is called, it see the modified a
.
Help link: http://robertnyman./2008/10/09/explaining-javascript-scope-and-closures/ .
本文标签: javascriptgoogle maps multiple markers clickeventStack Overflow
版权声明:本文标题:javascript - google maps multiple markers clickevent - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743954876a2567951.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论