来自XML的多条折线

时间:2015-10-18 07:16:19

标签: javascript xml google-maps google-polyline

我想在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);
    }
});

有人可以指出我忽略的内容吗?

1 个答案:

答案 0 :(得分:2)

是的,这是因为您只是通过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,但它们实际上是相同的。

演示 - &gt;的 http://jsfiddle.net/9sqastj1/