1

作为我的 last.fm/google maps 事件混搭的一部分,我必须将标记从 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 等的情况下添加闭包。除非这是唯一的解决方案之一?

非常感谢。

4

1 回答 1

1

隔离变量范围的一种简单方法marker是将调用包装在匿名函数中:

var map = ...

(function() {
    var image = ...
    var marker = ...
    ...
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });
})();

如此处所述,匿名函数将在其声明的范围内看到任何内容。所以在函数内部可以看到map,它在声明时就在作用域内。但在函数之外,marker是不可见的,因此匿名函数的重复克隆不会相互影响。

于 2011-03-06T14:44:32.797 回答