2013-04-22 68 views
0

我正在使用Google Maps API和Instagram API在地圖上顯示流行的圖像標記。一旦用戶選擇了一個,我想要在該位置拍攝的圖像的縮略圖顯示在信息氣泡中。我有兩個API工作得很好,但我無法弄清楚如何讓它們一起工作。我知道我將不得不面對範圍問題以便從$。(each)循環中獲取變量,但是我不知道如何在不使用return語句停止每個「循環」的情況下如何實現。而且,一旦我將它返回,它不會再是一個數組了嗎?下面是我的javascript:通過javascript中的函數傳遞數組變量

// get instagram info 

function requestJSON(urlToRequest) { 
     var headElement = document.getElementsByTagName("head")[0];   
     var newScriptTag = document.createElement('script'); 
     newScriptTag.setAttribute('type','text/javascript'); 
     newScriptTag.setAttribute('src',urlToRequest); 
     headElement.appendChild(newScriptTag); 
} 

function callThis(responseData) { 
    console.log(responseData); 
    $.each(responseData.data, function(i, data) { 
     //console.log(item); 
     var image = data.images.thumbnail.url; 
     var location = data.location; 
     if (location) { 
      $("<img/>").attr("src", image).appendTo("#showPics"); 
      // decimal will need to be rounded to .000000 
      var lat = data.location.latitude; 
      var lon = data.location.longitude; 
      console.log(lat); 
      console.log(lon); 
     } 
     else { 
      return; 
     } 
      }); 
} 

$(document).ready(function() { 
    $('p a').on('click',function(e) { 
     e.preventDefault(); 
     requestJSON('https://api.instagram.com/v1/media/popular?client_id=MYCLIENTID&callback=callThis'); 
    }); 
}); 



// get the map info 

function initialize() { 
    var mapOptions = { 
     center: new google.maps.LatLng(20, 0), 
     zoom: 2, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("map-canvas"), 
     mapOptions); 

    //hardcoded map info that I want to be an array of locations i.e. lat and long 
    var locations = [ 
      ['Somewhere a picture was taken', 33.86857, -117.8778], 

    ]; 

    var infowindow = new google.maps.InfoWindow(); 
    var marker, i; 

    for (i = 0; i < locations.length; i++) { 
     marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
     map: map 
     }); 
     google.maps.event.addListener(marker, 'click', (function(marker, i) { 
     return function() { 
      infowindow.setContent(locations[i][0]); 
      infowindow.open(map, marker); 
     } 
     })(marker, i)); 
    } 
} 
google.maps.event.addDomListener(window, 'load', initialize); 

回答

0

可能只是有一個數組,只是$.each之前宣佈作爲全球喜歡 - window.locationsArray = [](或者可能是普通的對象數組),填充它的$.each內和之後的迭代完成後,開始繪製包含在GMap上的locationsArray的點 -

$.each(locationsArray, function(index, value) { 

          var aLatLong = *--*Have the Lat+Longitude*--*; 
          var aContent = ""; 
          map_canvas.gmap('addMarker', { 
          'position':aLatLong 
          }).click(function() { 
          map_canvas.gmap('openInfoWindow', { content :'<p style="color:black;">'+value[2]+'</p><p style="color:black;"><b>'+'Views: '+aContent+'</b></p>' }, this); 
            }); 

            });