XML and Data Parsing
The Google Maps API exports a factory method for creating browser-neutral
XmlHttpRequest()
objects that work in recent versions of Internet Explorer, Firefox, and Safari. As with all XmlHttpRequest
s, any retrieved files must be on your local domain. The following example downloads a file called myfile.txt
and displays its contents in a JavaScript alert()
:var request = GXmlHttp.create(); request.open("GET", "myfile.txt", true); request.onreadystatechange = function() { if (request.readyState == 4) { alert(request.responseText); } } request.send(null);
The API also exports a simpler
GDownloadUrl()
method for typical HTTP GET requests that eliminates the need for XmlHttpRequest()
readyState
checking. The example above could be rewritten using GDownloadUrl()
like this:GDownloadUrl("myfile.txt", function(data, responseCode) { alert(data); });
You can parse an XML document with the static method
GXml.parse()
, which takes a string of XML as its only argument. This method is compatible with most modern browsers, but it throws an exception if the browser does not support XML parsing natively.In this example, we download a static file (
"data.xml"
) that contains a list of lat/lng coordinates in XML using the GDownloadUrl
method. When the download completes, we parse the XML with GXml
and create a marker at each of those points in the XML document.