1

Possible Duplicate:
change global variable inside javascript closure

I am having a problem storing data in a javascript global array . I can't figure out why the array is empty even though I have assigned it some elements.

Basically I have two functions: loadMarkers is called whenever a user clicks a button and gets some information from a url in JSON, parses that data and stores it in the global array. The other function is showMarkers that just iterates over the array and show all the markers, but that array is empty!

Thansks in advance.

var markers = [];


function loadMarkers(url) {

    markers = [];
    $.get(url, function(data) {

        var json = jQuery.parseJSON(data);

        for (var i = 0; i < json.length; i++) {

            // parsing json
            var lat = json[i].Latitude;
            var lng = json[i].Longitude;
            var id = json[i].ID;

            console.log(id); // this prints with no problems!

            // create new marker
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lng),
                title: id,
                html: "<p>" + "Info for container " + id + "</p>"
            });

            // add marker to markers array        
            markers.push(markers[i]);

            // add info window to marker
            google.maps.event.addListener(marker, "click", function() {
                infoWindow.setContent(this.html);
                infoWindow.open(map, this);
            });
        }
    });
}

function showMarkers() {
    for (i = 0; i < markers.length; i++)
        console.log(markers); // here I get an empty array!
        markers[i].setMap(map);
}
Community
  • 1
  • 1
nunos
  • 20,479
  • 50
  • 119
  • 154
  • Did you ensure that json.length > 0? – RonaldBarzell Nov 28 '12 at 16:23
  • The `$.get` is **asynchronous**. Oh and @MikeBonds is correct - it should be `markers.push(marker);` – Pointy Nov 28 '12 at 16:24
  • 5
    It looks like you are just pushing an empty index. markers.push(markers[i]); markers is the original array, and it is empty. so you are basically pushing it onto itself. – Mike Bonds Nov 28 '12 at 16:24
  • Don;t you mean to write "markers.push(marker)"? – ron tornambe Nov 28 '12 at 16:26
  • what a giant blunder. i was looking into the code for 5/10 minutes and couldn't figure that out... :shame: – nunos Nov 28 '12 at 16:28
  • @Pointy: `$.get` being asynchronous is why I get an `undefined` console log the first time I right the code, right? How can I "block" and wait for a response so that I don't get an `undefined`? – nunos Nov 28 '12 at 16:29
  • 1
    @nunos - you can't "block" (well you could make the ajax call synchronous, but that's generally a bad idea). You do have a callback function however, so you can do the work in there. – Pointy Nov 28 '12 at 16:33

3 Answers3

4

It seems like this line:

markers.push(markers[i]);

should instead be:

markers.push(marker);
Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
2

Maybe its the following code

// add marker to markers array        
markers.push(marker); // was markers[i]

Regarding your second question in the comments the $.get() method returns a jQuery deferred object which allows you to execute functions after method has finished.

$.get().done( function( ) {
    // your code
});
George Cummins
  • 28,485
  • 8
  • 71
  • 90
Bruno
  • 5,772
  • 1
  • 26
  • 43
1

There's a typo in the code:

markers.push(markers[i]);

should be:

markers.push(marker);

It can be surprisingly hard to spot this kind of typos by just looking at the code (it's like our brains are trained to let us read what we expect to read)... In this case the best approach to find quickly these kind of errors is to add a debugger; instruction in the code, and follow along the execution of the program through the devtools of your choice.

Bruno
  • 5,961
  • 6
  • 33
  • 52