【问题标题】:Google Map Infowindow Closure?谷歌地图信息窗口关闭?
【发布时间】:2011-03-06 13:58:44
【问题描述】:

作为我的 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 等的情况下添加闭包。除非这是唯一的解决方案之一?

非常感谢。

【问题讨论】:

    标签: javascript search google-maps mashup last.fm


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2013-10-04
      • 2014-04-06
      • 2013-02-05
      相关资源
      最近更新 更多