我想显示一个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元素,内循环通过每个linePoint内的line元素。

但是似乎我的脚本将所有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,但是它们实际上是相同的。

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

09-19 18:55