3

我試圖使用地圖API MarkerClusterer功能,沒有運氣:谷歌地圖API MarkerClusterer問題

var markersArray = []; 

function getMarkers(hours) {//5 

    if (markersArray) { 
     for (i in markersArray) { 
      markersArray[i].setMap(null); 
     } 
     markersArray.length = 0; 
    } 

    image = '/images/site/tw.png'; 

    $.ajax({ 
     url: "updateMarkers", 
     type:"POST", 
     data:{"hours": hours}, 
     success: function(data){ 
      data = $.parseJSON(data); 
      if (data.Locations.length>0) {//2 
        for (i=0; i<data.Locations.length; i++) {//1 
         loc = new google.maps.LatLng(data.Locations[i].lat, data.Locations[i].lng); 

         marker = new google.maps.Marker({ 
          position: loc, 
          map: map, 
          icon: image, 
          html: content 
         }); 

         markersArray.push(marker); 

         infowindow = new google.maps.InfoWindow({ 
          content: "holding..." 
         }); 

         google.maps.event.addListener(marker, 'click', function() { 
          infowindow.open(map, this); 
          infowindow.setContent(this.html); 
         }); 
        }//1 
       }//2 
      } 
     }); 

    var markerCluster = new MarkerClusterer(map, markersArray); 

}//5 

getMarkers(24); 

我已經看了所有的例子我能找到,雖然我試圖以一個Ajax內做到這一點回調函數我看不到其他區別。我在地圖上正常顯示標記,但沒有聚集效果。

+0

對於代碼格式感到抱歉 - 不知道發生了什麼:) – David 2011-05-25 06:57:13

回答

0

Ajax是異步的。在回調函數完成之前創建MarkerClusterer會發生什麼,因此沒有標記被推入全局數組markersArray。這只是我的頭頂,沒有任何測試,但看看它是否能解決問題。

var markersArray = [], markerCluster; 

function getMarkers(hours) {//5 

    if (markersArray) { 
     for (i in markersArray) { 
      markersArray[i].setMap(null); 
     } 
     markersArray.length = 0; 
    } 

    image = '/images/site/tw.png'; 

    $.ajax({ 
     url: "updateMarkers", 
     type:"POST", 
     data:{"hours": hours}, 
     success: function(data){ 
      data = $.parseJSON(data); 
      if (data.Locations.length>0) {//2 
        for (i=0; i<data.Locations.length; i++) {//1 
         loc = new google.maps.LatLng(data.Locations[i].lat, data.Locations[i].lng); 

         marker = new google.maps.Marker({ 
          position: loc, 
          map: map, 
          icon: image, 
          html: content 
         }); 

         markersArray.push(marker); 

         infowindow = new google.maps.InfoWindow({ 
          content: "holding..." 
         }); 

         google.maps.event.addListener(marker, 'click', function() { 
          infowindow.open(map, this); 
          infowindow.setContent(this.html); 
         }); 
        }//1 

        //Create the Cluster AFTER all markers are pushed into the markersArray, and make sure it's called within the callback function 
        markerCluster = new MarkerClusterer(map, markersArray); 
       }//2 
      } 
     }); 

}//5 

getMarkers(24);