Reputation: 591
So i'm having some trouble getting a variable created from an xml doc into a javascript function. Basic jist of it is i'm creating the variable infoX with some info collected from the xml file. Then trying to take that infoX variable and have it used in the google maps piece as the contentString variable that populates the info window in the google map. Heres a link: http://bit.ly/1eekyPw
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" language="javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<!--GMAP GOES HERE -->
<div id="map" style="width:300px; height: 200px"></div>
<script>
var infoX = '';
$(document).ready(function(){
var buildID= '0';
$.ajax({
type: "GET",
url: "buildings.xml",
dataType: "xml",
success: function(xml){
$(xml).find('marker[id='+buildID+']').each(function(){
sname = $(this).attr('name');
simage = $(this).attr('image');
sdescription = $(this).attr('description');
infoX = '<div id="content"><div id="siteNotice"></div><h1 id="firstHeading" class="firstHeading">'+sname+'</h1><div id="bodyContent"><img src="'+simage+'" style="float:left" />'+sdescription+'</div></div>';
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var contentString = infoX;
var infowindow = new google.maps.InfoWindow({
content: infoX
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize());
});
</script>
</body>
</html>
Thanks in advance!
Upvotes: 0
Views: 73
Reputation: 72
You are right in assuming that it has something to do with load time but not with the page load time but ajax load time. The problem is occurring because the initialize function is being called before the ajax request returns a value which makes infoX have the value of ''; To test this I looked at your page and dropped a breakpoint in chrome developer tools inside the success callback from the ajax request, and then one where infoX is used inside initialize() the breakpoint inside initialize() stopped execution and then execution was stopped inside the ajax success callback. Since infoX is used before the ajax request completed it is the value it was initialized to at the top of your script. if initialize was called inside the success of the ajax request the values should be set.
Upvotes: 1