2011-03-06 160 views
1

作爲我的last.fm/google地圖事件混搭的一部分,我必須將標記從last.fm API動態繪製到Google地圖上。Google Map Infowindow關閉?

這一切都很好,但是當我點擊標記時,只顯示最後一個infowindow(對於一個演出)。我知道這個理由,但是很難實現它。

目前我正在通過所有動態演出地點(座標)運行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等,除非這是唯一的一個解決方案?

很多很多,謝謝。

回答

1

一個簡單的方法你變量的作用域隔離是包裝調用一個匿名函數:

var map = ... 

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

如上所述here,匿名函數會看到什麼範圍內它被宣佈。因此函數內部可以看到map,它在聲明時處於範圍內。但在函數之外,是不可見的,所以匿名函數的重複克隆不會互相影響。

+0

謝謝,這看起來不錯! – cee 2011-03-06 14:57:30

+0

神奇,作品!非常感謝 – cee 2011-03-06 15:02:05