作为我的last.fm/google地图事件混搭的一部分,我必须将标记从last.fm API动态绘制到Google地图上。
这一切都很好但是当我点击标记时,只显示最后一个信息窗(对于一个演出)。我知道这个的原因但很难实现它。
目前我正在通过所有动态演出的位置(坐标)运行PHP循环,然后将其传递给javascript。这对我来说更有意义 - 我对PHP的了解比JS好得多:
<?php
foreach ($gigs->events->event as $js_event) {
$lat = $js_event->venue->location->children("geo",true)->point->children("geo",true)->lat;
$long = $js_event->venue->location->children("geo",true)->point->children("geo",true)->long;
$coords = "$lat,$long";
?>
var image = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=G|00CC99|000000',
new google.maps.Size(40, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32));
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $coords ?>),
map: map,
icon:image,
title: '<?php echo str_replace('\'','',$js_event->title) ." at ". str_replace('\'','',$js_event->venue->name) ?>'
});
var contentString = '<?php echo str_replace('\'','',$js_event->title) ." at ". str_replace('\'','',$js_event->venue->name)?>'
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
<? } ?>
如果没有完全重构循环到JS而不是PHP等,我怎么能添加闭包除非这是唯一的解决方案之一?
很多,非常感谢。
答案 0 :(得分:1)
隔离marker
变量范围的一种简单方法是将调用包装在匿名函数中:
var map = ...
(function() {
var image = ...
var marker = ...
...
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
})();
正如here所述,匿名函数将在声明它的范围内看到任何内容。因此,在函数内部可以看到map
,它在声明时在范围内。但是在函数之外,marker
是不可见的,因此匿名函数的重复克隆不会相互影响。