2015-04-09 2 views
-1

Я разрабатываю приложение, в котором я использую API API акс.k.a и API карт Google. Используя AJAX, я получаю первый набор изображений отфильтрованный от тег имя. В 1-м наборе мы получаем 20 изображений. Среди полученных изображений изображения, которые имеют широта и longitude info (geotagged images) отображаются на карте.Google Map не отображается при загрузке

Теперь, когда моя страница загружается, я не вижу карту. Но когда я нажимаю кнопку «Загрузить больше», чтобы получить следующий набор изображений, карта отлично работает с моими предыдущими изображениями.

Вот код для того, что происходит при загрузке страницы:

$(window).load(function() { 
    $.ajax({ 
     type: "GET", 
     url: "https://api.instagram.com/v1/tags/nyc/media/recent?client_id=02e****", 
     dataType:'JSONP', 
     success: function(result) { 
     onAction(result, 2, tag); 
     instaMap(result, 2, from); 
     } 
    }); 
}); 

Эти функции Называние:

/** 
    * [initialize description] 
    * Initialize the map with markers showing all photos that are geotagged. 
*/ 
var initialize = function(markers) { 
var bounds = new google.maps.LatLngBounds(), 
mapOptions = { 
    scrollwheel: false, 
    mapTypeId: 'roadmap', 
    center: new google.maps.LatLng(22.50, 6.50), 
    minZoom: 2 
}, 
gmarkers = [], 
map, 
positions, 
markCluster; 

markers = remDuplicate(markers); 

// Info Window Content 
var infoWindowContent = []; 
for (var j = 0; j < markers.length; j++) { 
    var content = [ 
    '<div class="info_content">' + 
    '<h3>' + markers[j][2] + '</h3>' + 
    '<a href="' + markers[j][3] + '" target="_blank">' + 
    '<img src="' + markers[j][4] + '" style="z-index:99999">' + '</a>' + 
    '</div>' 
    ]; 
    infoWindowContent.push(content); 
} 

// Display a map on the page 
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
map.setTilt(45); 

// Display multiple markers on a map 
var oms = new OverlappingMarkerSpiderfier(map); 
var infoWindow = new google.maps.InfoWindow(), marker, i; 

// Loop through our array of markers & place each one on the map 
for(i = 0; i < markers.length; i++) { 
    positions = new google.maps.LatLng(markers[i][0], markers[i][1]); 
    marker = new google.maps.Marker({ 
    position: positions, 
    map: map, 
    animation:google.maps.Animation.BOUNCE, 
    title: markers[i][2] 
    }); 

    oms.addMarker(marker); 

    // Allow each marker to have an info window 
    google.maps.event.addListener(marker, 'click', (function(marker, i) { 
    return function() { 
     infoWindow.close(); 
     infoWindow.setContent(infoWindowContent[i][0]); 
     infoWindow.open(map, marker); 
     map.setCenter(marker.getPosition()); 
    }; 
    })(marker, i)); 

    gmarkers.push(marker); 
} 

google.maps.event.addListener(map, 'click', function() { 
    infoWindow.setMap(null); 
}); 

markCluster = new MarkerClusterer(map, gmarkers); 

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once) 
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) { 
    map.setZoom(2); 
    google.maps.event.removeListener(boundsListener); 
}); 

}; 

/** 
    * [onAction] 
    * OnAction() function helps in loading non-geotagged pics. 
    * 
    * @param {[type]} result [Result retruned from the Instagram API in json format] 
    * @param {[type]} likey [hearts the user has entered as per which the posts will be filtered] 
    */ 
    var onAction = function (result, likey, tag) { 
$('.load-pics').remove(); 

if (result.pagination.next_url) { 
    paginate = removeURLParameter(result.pagination.next_url, 'count'); 
} 

$.each(result, function(key, value) { 
    if (key === 'data') { 
    $.each(value, function(index, val) { 
     liked = val.likes.count; 
     link = val.link; 
     imgUrl = val.images.low_resolution.url; 
     locations = val.location; 

     if (liked >= likey) { 
     if (locations === null) { 
      output = '<li class="img-wrap">' + '<div class="main-img">' + 
      '<a href="' + link + '" target="_blank">' + 
      '<img src="' + imgUrl + '" ><span class="hover-lay"></span></a>' +'<p>' + 
      '<span class="heart"></span><span class="likes-no">' + liked + '</span>' + 
      '<span class="comment-box"></span><span class="comment-no">' + 
      val.comments.count + '</span> ' + '</p>' + '</div>' + 
      '<div class="img-bottom-part">'+ '<a href="" class="profile-pic"></a>' + '<div class="headin-hastag">' + 
      'by ' + '<h2>Sebastien Dekoninck</h2><a href="" class="has-trand">#hello <span>#kanye</span> #helloagain #tagsgohere</a></div>' 
      +'</div></li>'; 
      $('#instafeed').append(output); 
     } 
     } 
    }); 
    } 
}); 

if ($('#instafeed').children().length === 0) { 
    alert('There are no pics with ' + likey + ' likes or #' + tag + ' was not found.'); 
} else { 
    // $('.not-geo').remove(); 
    // $('#instafeed').before('<button class="not-geo">Click To See Images That Are Not Geotagged <img src="assets/imgs/down.png" ></button>'); 
} 
$('#instafeed').append('<div class="load-pics"><button id="show-more">Show more <span></span></button> </div>'); 
}; 

/** 
* [instaMap] 
* instaMap() will be the function which will deal with all map based functionalities. 
*/ 
var instaMap = function(result, likey, from) { 
$('.load-mark').remove(); 

if (result.pagination.next_url) { 
    pagiMap = removeURLParameter(result.pagination.next_url, 'count'); 
} 
$.each(result, function(key, value) { 
    if (key === 'data') { 
    $.each(value, function(index, val) { 
     liked = val.likes.count; 
     link = val.link; 
     imgUrl = val.images.low_resolution.url; 
     locations = val.location; 

     if (liked >= likey) { 
     if (locations && locations.latitude !== null) { 
      tempArr = [ 
      locations.latitude, 
      locations.longitude, 
      val.user.username, 
      val.link, 
      val.images.low_resolution.url 
      ]; 
      mark.push(tempArr); 
     } 
     } 
    }); 
    } 
}); 
if (mark.length) { 
    initialize(mark); 
    $('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>'); 
} else { 
    alert('No geotagged pics found in the retrieved set. Click see more'); 
    $('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>'); 
} 
}; 

Я создал См больше кнопку, чтобы получить следующий набор изображений и загрузить их на Карту. Когда вы нажимаете больше, все работает нормально. Не знаю, почему это происходит. Console.log не показывает никаких ошибок. Кроме того, все значения, которые я подаю, поступают надлежащим образом. Я даже пытался очистить кеш. Не уверен, почему это происходит.

+0

Где ваша функция инициализации вызывается из? – duncan

+0

Извините, не добавляйте эти строки. Теперь я добавил. Я звоню через функцию instaMap. –

+1

Можете ли вы поделиться живым кодом, в котором вы разместили? – itzmukeshy7

ответ

2

Если instaMap - это функция, которая будет обрабатывать все ваши функции на основе карты, она должна быть той, которая загружает карту в вашу функцию $ (window) .load();

В противном случае, если вы хотите Google карт для загрузки на начальной загрузке окна нужно поставить ниже там:

google.maps.event.addDomListener(window, 'load', initialize); 
 

Смежные вопросы