The function performs the following steps:
- Retrieves an XML document through AJAX.
- Identifies relevant information within the document.
- Dynamically converts it into an object using a for loop.
How can I access this generated object outside of the function?
Sample Code:
XML File:
<root>
<config>
<station>Station_One</station>
<station>Station_Two</station>
<station>Station_Three</station>
</config>
</root>
JS file with station coordinates:
var stations = {
'Station_One': {
lat: 78.782762
, lng: 17.917843
, name: 'Nowhere'
},
'Station_Two': {
lat: -0.829439
, lng: -91.112473
, name: 'Isla Isabela'
},
'Station_Three': {
lat: 15.066156
, lng: -23.621399
, name: 'Cape Verde'
}
Script:
function addRoute() {
xhr = createHttpRequest(); //This function returns an XMLHttpRequest()
var url ="urlhere"; //assume valid URL
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var doc = xhr.responseXML;
var routeStations={};
config=doc.getElementsByTagName("station");
for (i=0;config.length>i;i++) {
//Successfully extracts station values and stores them in currentStation
var currentStation = config[i].childNodes[0].nodeValue;
//currentStation is then used as a reference to find the values stored in the JS file
var lat = stations[currentStation].lat;
var lng = stations[currentStation].lng;
//routeStations Object is created dynamically
routeStations[currentStation] = {lat: lat, lng: lng}
} //end for loop
//alert(routeStations); routeStations object is created successfully
// but will not be available beyond this point
//return routeStations; did not work for me
} //end readyState && status
} // end onreadystatechange
xhr.open("GET",url,true);
xhr.send(null);
}
How do I make this object accessible by other functions?
To clarify, I aim to utilize this object in another function. The intention is to use these coordinates to draw a polyline with the Google Maps API.
Note: This function is triggered by an onChange event, therefore, a new object must be created each time the event occurs on top of the existing one.