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