Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

154 Part III — Google Map Hacks


To download an item you send a request for the specified file, in this case ch09-04.xml:
request.open(‘GET’,’ch09-04.xml’, true);

Rather than blocking the execution of the rest of the JavaScript within the HTML until the
load has been completed (which could be a long delay), instead you define a function that will
be called when the status of the download object changes. You can do this inline; state 4 indi-
cates a successful retrieval, so you can then start parsing the document:
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlsource = request.responseXML;

The responseXMLfield of the request contains a DOM representation of the XML data,
which in turn means that you can use the same functions and methods that you use to manipu-
late HTML in the document. Thus you can use a list of the XML tags with a specific name
using getElementsByTagName:
var markerlist = xmlsource.documentElement.getElementsByTagName(“marker”);

This generates an array of the individual tag elements. You can extract the information embed-
ded into the attributes of a tag within each element by using the getAttribute()method
on that element, specifying the attribute name. For example:
markerlist[i].getAttribute(“lng”)

You can repeat the same process on the same tag multiple times to get information out of mul-
tiple attributes.

Putting this together, and replacing the earlier addmarker()elements in the previous
HTML-only examples with a model that dynamically loads the XML and then generates the
markers, is shown in Listing 9-4.

Listing 9-4:Parsing Your XML File into Information

function onLoad() {
if (GBrowserIsCompatible()) {
infopanel = document.getElementById(“infopanel”);
map = new GMap(document.getElementById(“map”));
map.centerAndZoom(new GPoint(-0.64,52.909444), 2);

var request = GXmlHttp.create();
request.open(‘GET’,’ch09-04.xml’, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlsource = request.responseXML;
var markerlist = ;
xmlsource.documentElement.getElementsByTagName(“marker”);
for (var i=0;i < markerlist.length;i++) {
addmarker(parseFloat(markerlist[i].getAttribute(“lng”)),
parseFloat(markerlist[i].getAttribute(“lat”)),
markerlist[i].getAttribute(“title”));
Free download pdf