Reading XML files in JavaScript requires using the XMLHttpRequest object that is built into all of the major web browsers. Unfortunately, creating this object requires slightly different code depending on the user's browser (one version of the code for Internet Explorer and another for the rest of the major browsers like Chrome, Firefox and Safari). Fortunately, JavaScript frameworks like jQuery have methods for "abstracting away" the messy details of working with the XMLHttpRequest object. In this part of the lesson, we'll see how jQuery's ajax() method can be used to read the contents of a file into memory. We'll then use other jQuery methods to parse the XML after it's been read in.
- First, create a copy of your page from Project 4 (the Jen & Barry's ice cream map) and remove the code in the initMap() function that adds the markers. You can use this version of the code if you like.
-
Set up a reference to jQuery just above the existing script element:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
References to the jQuery EasyUI JavaScript library and stylesheet aren't needed for this example.
-
In initMap(), insert a call to jQuery's ajax() method that passes the name of the XML file and stores the retrieved XML in a variable called xmlDoc using code like this:
$.ajax({ url: "candidate_cities.xml", dataType: "xml", success: function(xmlDoc){ // data processing code will go here }});
When using the ajax() method, only the url property is required. Other optional settings are detailed in the method's documentation. In this context, we're setting the dataType property (specifying what kind of data we're reading in; other types that might be used in other contexts include "html", "text" and "json") and a function to execute if and when the request is a success. Here we're embedding the success function within the larger ajax() statement. jQuery passes the data to the success function so that it can be processed and since we're reading in XML data here, we call this variable xmlDoc. Because we've specified a dataType of xml, the data in xmlDoc is recognized as a set of XML DOM elements and thus ready to be handled using jQuery's DOM manipulation methods.
- Inside the ajax() code block, insert the following code:
$(xmlDoc).find("pt").each(function() {
});
This code uses jQuery's find() method to find all of the pt elements in the XML data. It then appends onto the find() method call a call to the each() method. This code essentially says, "Execute this function (which is empty at the moment) for each pt element found in xmlDoc." -
Within the each() method's embedded inline function, insert the following line:
var name = $(this).attr("name");
This line makes use of the fact that the element being processed in the current iteration of the each() loop can be referenced using the this keyword. With "this" representing an XML element, we use the attr() method to retrieve the value held by one of its attributes (specifically the name attribute).
-
Add a similar line to retrieve the current element's population value:
var pop = $(this).attr("population");
When obtaining the latitude/longitude values, we need to make sure that the returned value gets stored as a number and not as a string. Attribute values are always returned as strings, so we can use JavaScript's parseFloat() function to convert the string to a floating point number. -
Get the x and y values as follows:
var x = parseFloat($(this).attr("x")); var y = parseFloat($(this).attr("y"));
With the latitude and longitude values obtained, the rest of the code inside the loop is fairly straightforward.
- Next, create a new LatLng object:
var pt = new google.maps.LatLng(lat, lng);
-
Finally, pass those variables as arguments to the createMarker() function:
createMarker(pt, name, pop);
-
Save the document and test it. You may refer to my version of the page if yours is not working.
Note
You can test the copy of your page stored on your machine. Just make sure you have the candidate_cities.xml and cone.png files in the same folder with the page. Likewise, if you decide to run it from your personal web space, be sure to upload those files.
With that, you've seen how marker data can be parsed from XML data stored on disk. Now we'll shift to discussing the topic of relational databases. After working through some database fundamentals, we'll come back to the Jen & Barry's scenario and see how to script the retrieval of the cities from a database and output the data as XML so that it can be consumed by a page just like the one created here.