我可以使用以下代码实现多个标记:
<?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);
}
问题在于google.maps.event.addListener
功能。如果我使用该变量i
,则返回undefined。但是,如果我使用硬编码值(1、2 或 3),则返回标记对象。markerClick()
console.log()
console.log()
让我感到困惑的是,为什么如果我使用循环变量,参数不会被传递i
,但如果我硬编码一个值,它就可以工作。我在这里想念什么?