2013-01-23 32 views
2

我試圖在點擊標記時動態更改標記的圖標。我有地圖(通過數據庫查詢收集)上的多個標記,這是代碼我目前使用 - 這些都是標準的東西:谷歌地圖 - setIcon代碼使標記消失

function initialize() { 
     var myOptions = { 
      center: new google.maps.LatLng(-30,135), 
      zoom: 4, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     var map = new google.maps.Map(document.getElementById("map"), 
      myOptions); 
     var bikeicon = "images/bike.png"; 


    <?php 
    $result=mysql_query("select * from sites"); 
    while($row=mysql_fetch_assoc($result)){ 
     ?> 
     marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(<?php echo $row['Latitude']; ?>, <?php echo $row['Longitude']; ?>), 
     map: map, icon: bikeicon}); 

     infoWindow = new google.maps.InfoWindow(); 

     marker.html="<?php echo stripslashes($row['ShortDesc']); ?>"; 

     google.maps.event.addListener(marker, 'click', function(){ 
      //show infowindow 
      infoWindow.setContent(this.html); 
      infoWindow.open(map, this); 
      //change icon color 
      var icon = new google.maps.MarkerImage({ url:"http://jovansfreelance.com/bikestats/images/bike_red.png"}); 
       this.setIcon(icon);  //why doesn't this work? 

     }) 
     <?php 
    } 
    ?> 

} 

信息窗口代碼工作正常,但操作SetIcon代碼只是使標記消失並且不顯示新的標記圖標。新圖標的URL是有效的,您可以在瀏覽器中打開它看到。

所以有誰能告訴我爲什麼這個代碼不工作?

回答

2

MarkerImage預計URL作爲第一個參數,而不是它包含的URL的對象。

但是你應該避免使用MarkerImage的,它的棄用。

,您也可以直接將URL傳遞的setIcon。

可能的方法(一切都會給出相同的結果):

 
    //use the MarkerImage-object 
this.setIcon(icon);  

    //simply use the url 
this.setIcon('http://jovansfreelance.com/bikestats/images/bike_red.png'); 

    //using an google.maps.Icon-object 
this.setIcon({url:'http://jovansfreelance.com/bikestats/images/bike_red.png'});