I want to display multiple polylines from an XML file:
<lines>
<line>
<linePoint lat="47.608940" lng="-122.340141"/>
<linePoint lat="47.613590" lng="-122.344391"/>
<linePoint lat="47.624561" lng="-122.356445"/>
</line>
<line>
<linePoint lat="47.616600" lng="-122.344491"/>
<linePoint lat="47.627661" lng="-122.356545"/>
</line>
</lines>
I believe that the script should iterate twice - the outer loop going through line
elements and the inner loop going through linePoint
elements within each line
.
But it seems that my script dumps all 5 linePoint
into a single polyline instead of creating 2 polylines.
downloadUrl("createXML.php", function(data) {
var xml = data.responseXML;
var line = xml.documentElement.getElementsByTagName("line");
// Read each line
for (var a = 0; a < line.length; a++) {
var linePoint = xml.documentElement.getElementsByTagName("linePoint");
var path = [];
// Read markers on each line
for (var i = 0; i < linePoint.length; i++) {
var lat = parseFloat(linePoint[i].getAttribute("lat"));
var lng = parseFloat(linePoint[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
path.push(point);
}
var polyline = new google.maps.Polyline({
path: path
});
polyline.setMap(map);
}
});
Can someone please point out what I'm overlooking?
Yes, that is because you just extract all
<linePoint>
's in one chunk by getElementsByTagName("linePoint")
(elements in plural). Iterate over <line>
's and for each <line>
iterate over its <linePoint>
's :
function showPolyLines() {
var parser = new DOMParser();
var xml = parser.parseFromString(responseXML, "application/xml");
var line = xml.querySelectorAll("line");
for (var l = 0; l < line.length; l++) {
var path = [],
linePoints = line[l].querySelectorAll('linePoint');
for (var p = 0; p < linePoints.length; p++) {
var linePoint = linePoints[p],
lat = parseFloat(linePoint.getAttribute("lat")),
lng = parseFloat(linePoint.getAttribute("lng")),
point = new google.maps.LatLng(lat, lng);
path.push(point);
}
var polyline = new google.maps.Polyline({
path: path,
//just to be sure the lines actually is shown on the map :)
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
}
}
I am using a DOMParser to substitute xml.documentElement
because I dont have a real responseXML
in my fiddle test, but they are practically the same.
demo -> http://jsfiddle.net/9sqastj1/