I want to access the javascript variable called locations
outside of its assigned method.
Javascript code:
$(document).ready(function() {
var locations;
console.log('document ready');
function initializeMap() {
$.ajax({url: "getlocation.php",
success: function(result){
locations = $.parseJSON(result);
alert(locations);
}
});
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initializeMap();
});
How can I get the json parsed data passed to the locations variable so I can get data outside of its assigned method and into the loop?
Here is the finished code that solves my problem:
$(document).ready(function() {
console.log('document ready');
function initializeMap() {
var locations;
$.ajax({url: "getlocation.php",
success: function(result){
alert(result);
locations = $.parseJSON(result);
alert(locations);
}
});
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initializeMap();
});
"Pass by Reference" and "Pass by Value" are two programming terms that describe how a method behaves when passing a variable into a method.