2011-10-09 38 views
2

這是我在地圖上繪製多邊形的代碼,它不起作用。請告訴我我做錯了什麼。將google.maps.latlng添加到循環中的數組中

如果我加分手動像這樣:

points.push(new google.maps.LatLng(51.35020072, -2.978521717)); 
points.push(new google.maps.LatLng(51.35047285, -2.971755353)); 
points.push(new google.maps.LatLng(51.34943740, -2.969097019)); 

,而不是使用它工作正常循環。有任何想法嗎?

function drawpolygon(areaid) { 

    var points = []; 

    $.ajax({ 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     url: "polygons.asmx/GetPolygonsByArea", 
     data: '{ id: "' + areaid + '" }', 
     dataType: "json", 
     success: function (msg) { 
      var c = eval(msg.d); 
      for (var i in c) { 

       var lat = parseFloat(c[i][1]); 
       var lng = parseFloat(c[i][2]); 

       points.push(new google.maps.LatLng(lat, lng)); 

      } 
     } 
    }); 

    var Area; 

    Area = new google.maps.Polygon({ 
     paths: points, 
     strokeColor: "#204F68", 
     strokeOpacity: 0.8, 
     strokeWeight: 2, 
     fillColor: "#A1CBE2", 
     fillOpacity: 0.35 
    }); 

    Area.setMap(map); 

    google.maps.event.addListener(Area, 'click', showArrays); 
    infowindow = new google.maps.InfoWindow(); 
} 

回答

5

我不確定你的意思是「手動添加點」,但我認爲問題在於ajax調用是異步的。因此,您正在調整「$ .ajax(...)」,然後直接跳到創建區域之前您的points數組中有任何內容的代碼:您的成功函數的異步調用尚未發生。

嘗試重新安排您的代碼,以便創建Area並在循環之後立即在成功函數中執行setMap(map)調用。

+0

實際上大聲笑了......昨天晚上花了三個小時工作後,我看到了你的答案,並將代碼拖入成功函數中,並且它第一次完美運行。非常感謝 :) –

相關問題