0

I am trying to get map coordinates of business listing from a JSON file that I have. The json is working correctly, but the coordinates are not being saved to my array. The array always returns empty. What am I doing wrong?

var locations = new Array();
var contents = new Array();
$.getJSON('listings/json', function(data) {
    $.each(data, function(i, listing) {
        var loc = new Array(listing.latitude, listing.longitude);
        locations.push(loc);
        contents.push('<div class="infobox"><div class="infobox-header"><h3 class="infobox-title"><a href="#">' + listing.listing_title + '</a></h3><h4 class="infobox-subtitle"><a href="#">Manhattan 5, NYC</a></h4></div><div class="infobox-picture"><a href="#"><img src="' + listing.preview_path + '" alt=""></a><div class="infobox-price">$ 2,000</div></div></div>');
    });
});

I get this problem with both the locations array and the contents array. Any ideas?

Nope
  • 22,147
  • 7
  • 47
  • 72
ShoeLace1291
  • 4,551
  • 12
  • 45
  • 81
  • 2
    Where are you reading them? $.getJSON is async so check the values inside the function you pass to it rather than after the call – Alex K. Jan 05 '17 at 10:47
  • Could you please post a full code with a sample JSON? – Eddie Jan 05 '17 at 10:48
  • Are you sure the 'data' returned from the 'listings/json' is an array? because it's most likely an object wrapping an array. – Ovidiu Dolha Jan 05 '17 at 10:49
  • yes, it is an object. that's why i call the coordinates with listing.latitude – ShoeLace1291 Jan 05 '17 at 10:52
  • and to the mod that marked this as duplicate, the issue has nothing to do with the json. I've tested the output by logging listing.latitude in console and it works perfectly. The issue is adding the info to an array. – ShoeLace1291 Jan 05 '17 at 10:53
  • 1
    But where are you doing it? You cannot examine `locations` *after* the $.getJSON call as $.getJSON may not have completed at that point, only within the function where you call $.each is the data guaranteed to exist. – Alex K. Jan 05 '17 at 11:08

0 Answers0