Search code examples
ajaxgoogle-mapsgoogle-maps-api-3instagraminstagram-api

Google Map doesn't appear on load


I am developing an app where I use 2 API's a.k.a Instagram API and Google Map API. Using AJAX, I get the first set of Images filtered by a tag name. In the 1st set we receive 20 images. Among the received images, the images that have the latitude and longitude info (geotagged images) are displayed on the map.

Now the first time when my page loads, I cannot see the map. But when I press the load more button to get the next set of images, the Map works fine showing my previous images too.

Here is the code for what happens on page load:

$( 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);
      }
    });
});

These are the functions being called:

 /**
  * [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>');
}
};

I have created a See More button to retrieve the next set of images and load those on the Map. When clicking see more, everything seems to work fine. Not sure why it's happening so. Console.log does not show any error. Also, all the values I feed does flow appropriately. I even tried clearing cache. Not sure, why it's happening.


Solution

  • If instaMap is the function which is going to handle all your map based functionality, it has to be the one that loads map in your $( window ).load function ();

    Otherwise, if you want Google maps to load on initial window load you need to put below in there:

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