最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - google maps multiple markers clickevent - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

Tipical 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/ .

发布评论

评论列表(0)

  1. 暂无评论