2014-02-16 31 views
1

我想通過一個json數組圖像循環,將圖像添加到地圖上的標記。由於JavaScript是異步的,它會導致我的問題,我想等待圖像加載之前加載到我的地圖,並不能讓我的圖像加載之前循環完成。這是可能實現的,因爲我試圖用回調來實現,但無法實現這個工作。在一個循環中的javascript onload事件

for (var i = 0; i < jsonObj.potholes.length; i++) 
{ 
     var image = new Image(); 



       image.src = "data:image/png;base64," + jsonObj.potholes[i].image; 
       image.onload = function() 
       { 
        //alert("image loaded"); 
        EXIF.getData(image, function() 
        { 
         otn = parseInt(EXIF.getTag(image, "Orientation")); 
         dataURL = drawCanvas(otn, image).toDataURL(); 

         var circle = L.circle([jsonObj.potholes[i].lat, jsonObj.potholes[i].lon], 18, { 
          color: 'yellow', 
          fillColor: 'red', 
          fillOpacity: 0.5 
         }).addTo(markersLayerGroup).bindPopup("Pothole ID " + jsonObj.potholes[i].id 
           + "<br />Location " + city[i] + "," + street[i] + 
           "<image src = '" + dataURL + "'></image>"); 


        }); 



} 

回答

1

您應該實現(使用if)異步循環:

(function (ondone) { 
    var index = 0; 
    nextStep(); 

    function nextStep() { 
     if (index >= jsonObj.potholes.length) { 
      if (ondone) 
       ondone(); 
      return; 
     } 

     var i = index++; 
     var image = new Image(); 

     image.src = "data:image/png;base64," + jsonObj.potholes[i].image; 
     image.onload = function() { 
      //alert("image loaded"); 
      EXIF.getData(image, function() { 
       otn = parseInt(EXIF.getTag(image, "Orientation")); 
       dataURL = drawCanvas(otn, image).toDataURL(); 

       var circle = L.circle([jsonObj.potholes[i].lat, jsonObj.potholes[i].lon], 18, { 
        color: 'yellow', 
        fillColor: 'red', 
        fillOpacity: 0.5 
       }).addTo(markersLayerGroup).bindPopup("Pothole ID " + jsonObj.potholes[i].id 
         + "<br />Location " + city[i] + "," + street[i] + 
         "<image src = '" + dataURL + "'></image>"); 

       nextStep(); 
      }); 
     } 
    } 
})(function() { alert("Done!"); }); 

您也可以使用承諾的,例如:JavaScript: Async Promise "while loop"