gpt4 book ai didi

javascript - 来自 XML 的多段线

转载 作者:行者123 更新时间:2023-12-02 15:32:47 24 4
gpt4 key购买 nike

我想显示 XML 文件中的多条折线:

<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>

我认为脚本应该迭代两次 - 外部循环遍历 line 元素,内部循环遍历每个 line 内的 linePoint 元素>.

但我的脚本似乎将所有 5 个 linePoint 转储到一条折线中,而不是创建 2 条折线。

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);
}
});

有人可以指出我忽略了什么吗?

最佳答案

是的,那是因为你刚刚提取 all <linePoint>getElementsByTagName("linePoint") 的一大块(复数元素)。迭代<line>和对于每个 <line>迭代其 <linePoint>的:

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);
}
}

我正在使用DOMParser替代xml.documentElement因为我没有真正的responseXML在我的 fiddle 测试中,但它们实际上是相同的。

演示 -> http://jsfiddle.net/9sqastj1/

关于javascript - 来自 XML 的多段线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33195328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com