简体   繁体   English

多个标记的奇怪点击问题:Google Map API

[英]Multiple Marker Strange Click Issue : Google Map API

I'm able to implement multiple markers by using the following code: 我可以使用以下代码来实现多个标记:

<?php foreach($dummy as $cid=>$data)
{   ?>
    var myLatlng = new google.maps.LatLng(<?php echo $data['lat']; ?>,<?php echo $data['lon']; ?>); 
    var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: "<?php echo $data['name']; ?>"
    });
    icons[j] = marker;
    maps[0] = map;    
    j++;
<?php  
}   
?>  
for(var i = 0; i < icons.length; i++)
{       
   google.maps.event.addListener(icons[i], 'click', function(){
    markerClick(icons[i], maps[0]); // this is the problem area
    // markerClick(icons[0], maps[0]); // this works
    // markerClick(icons[1], maps[0]); // so does this
   });  
}   

function markerClick(marker_argument, map){     
    console.log(marker_argument);        
 }

The issue is with the google.maps.event.addListener function. 问题出在google.maps.event.addListener函数。 If I use the variable i , then markerClick() 's console.log() returns undefined . 如果我使用变量i ,那么markerClick()console.log()返回undefined However if I use a hardcoded value (1, 2, or 3), console.log() returns the marker object. 但是,如果我使用硬编码的值(1、2或3), console.log()将返回标记对象。

What baffles me is why the argument is not being passed if I use the loop variable i , but works if I hardcode a value. 令我感到困惑的是,如果我使用循环变量i ,为什么不传递参数,但是如果我对值进行硬编码,则可以使我困惑。 What am I missing here? 我在这里想念什么?

.addListener循环包装在JavaScript闭包中,它应该可以工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM