In this example, we download a static file ("data.xml") that contains a
list of lat/lng coordinates in XML using the GDownloadUrl
method. It retrieves the resource from the given URL and calls the onload function
with the text of the document as first argument, and the HTTP response status code as the
second. The HTTP status code for success is 200. Since there is no HTTP status code
returned for
requests that time out, GDownloadURL will return a status of -1 and null
data for timeouts.
You can read more about HTTP status codes here.
In this example, we process the data if the request was successful, and then alert messages if the request has timed out or errored. In your own applications, you may decide to do more or less error checking, depending on your needs.
When the download completes, we parse the XML with GXml
and create a marker at each of those
points in the XML document.
// Download the data in data.xml and load it on the map. The format we
// expect is:
// <markers>
// <marker lat="37.441" lng="-122.141"/>
// <marker lat="37.322" lng="-121.213"/>
// </markers>
GDownloadUrl("data.xml", function(data, responseCode) {
// To ensure against HTTP errors that result in null or bad data,
// always check status code is equal to 200 before processing the data
if(responseCode == 200) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
map.addOverlay(new GMarker(point));
}
} else if(responseCode == -1) {
alert("Data request timed out. Please try later.");
} else {
alert("Request resulted in error. Check XML file is retrievable.");
}
});
View example (async.htm). This example uses the external XML data file data.xml.