我正在使用 Google Maps API 和 Instagram API 在地图上显示流行的图像标记。一旦用户选择了一个,我希望在该位置拍摄的图像的缩略图显示在信息气泡中。我让这两个 API 分别工作得很好,但我不知道如何让它们一起工作。我知道我必须面对范围问题才能从 $.(each) 循环中取出变量,但我不知道如何在不使用 return 语句停止每个“循环”的情况下这样做。而且,一旦我返回它,它就不再是一个数组了,不是吗?这是我的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);