Answer the question
In order to leave comments, you need to log in
Asynchronously loading XML and Google Maps in jQuery?
Situation: an XML file and Google maps are loaded in order to display data from XML on it. Everything is done asynchronously, it is required to track when both requests are completed.
The only easy way I've found is Deferred objects in jQuery.
We write
function loadXML() {<br/>
return $.ajax({ url: 'data.xml', dataType: 'xml' });<br/>
}
$.when( loadXML(), ... ).then(function(){<br/>
doSomethind();<br/>
});
function loadScript() {<br/>
var script = document.createElement("script");<br/>
script.type = "text/javascript";<br/>
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";<br/>
document.body.appendChild(script);<br/>
}<br/>
Answer the question
In order to leave comments, you need to log in
Solution:
in short - when loading the map with your hands, create a deferred-object, set its resolve() when loading the map with callback in
full:
function loadXML() { return $.ajax({ url: 'data.xml', dataType: 'xml' }); } function loadMap() { dfd = $.deferred(); varscript = document.createElement("script"); script.type = "text/javascript"; script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=finishMapLoading"; document.body.appendChild(script); return dfd.promise(); } function finishMapLoading() { dfd.resolve(); } function loadData() { varLMap = loadMap(); var LXML = loadCoupons(); $.when( LMap, LXML ).then( function() { doSomethingAwesome(); }); } window.onload = function() { loaddata(); }
For jquery there is a magical sequential query plugin. Tobish until the first one is processed. the second one will not be sent.
code.google.com/p/jquery-ajaxq/
And by the way… what's stopping you from inserting your loadScript function into the success event of the ajax request? this way it will be called when the data has already arrived + it can be passed as a function parameter
<script type="text/javascript" src="http://google.com/jsapi"></script>
<script>
var map;
google.load("maps", "3", {"callback" : mapsLoaded, "other_params" : "sensor=false"});
function mapsLoaded() {
var myOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
var markersKML = new google.maps.KmlLayer('http://your-site.com/points.kmz', {'map' : map, preserveViewport : true });
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question