I am having a problem with asynchronous $.ajax request. I am trying to download JSON data from restaurant-location.php
and load the data into array locations
. Then I need to iterrate through this array inside of initMap
function. When I print array locations
into the console i get undefined
result. I assume that the problem is with a call back function but I just can't figure it out. Any help would be greatly appreciated!
var locations = [];
window.onload = function downloadLocations() {
$.ajax({
type: "GET",
url: '/restaurant-locations.php',
success: function(data) {
console.log(locations); //will print out the location array
initMap(data)
},
});
}
console.log(locations); //will NOT print out the location array
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(10,-10),
zoom: 15
for ( var i = 0; i < locations.length; i++ ) {
var street = locations[i].street;
var city= locations[i].city;
more code ....
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&v=3&callback=initMap">
</script>