谷歌地图API无法从Array设置PolyLine

时间:2015-01-09 03:02:51

标签: javascript arrays google-maps-api-3

我尝试将坐标添加到折线但不起作用 但是,当我通过手动分配它时,它就是工作。

如何通过数组来完成它的工作。

var lat=[13.698090113461573,13.72771754374393,13.732881766645967,13.737967711523885];
    var lng=[100.75223565101624,100.74861466884613,100.69132804870605,100.56249350309372];

    // HERE IT DOESN"T WORK
    var poly = new Array();    
    for (var j=0;j<lat.length;j++){
    var pos = new google.maps.LatLng(lat[0],lng[0])
    poly.push(pos);
    }

    // HERE IT'S WORK
    var poly = [
    new google.maps.LatLng(lat[0], lng[0]),
    new google.maps.LatLng(lat[1], lng[1]),
    new google.maps.LatLng(lat[2], lng[2]),
    new google.maps.LatLng(lat[3], lng[3])
  ];

  console.log(poly);

  var Path = new google.maps.Polyline({
    path: poly,
    geodesic: true,
    strokeColor: '#ff004c',
    strokeOpacity: 1.0,
    strokeWeight: 5
  });
  Path.setMap(map);

2 个答案:

答案 0 :(得分:2)

我认为你应该写变量j而不是零数字

var poly = new Array();    
for (var j=0; j<lat.length; j++) {
    var pos = new google.maps.LatLng(lat[0],lng[0])
    poly.push(pos);
}
像这样:

var poly = new Array();    
for (var j = 0; j<lat.length; j++) {
    var pos = new google.maps.LatLng(lat[j],lng[j])
    poly.push(pos);
}

答案 1 :(得分:1)

代码就像这样

var lat=[13.698090113461573,13.72771754374393,13.732881766645967,13.737967711523885];
    var lng=[100.75223565101624,100.74861466884613,100.69132804870605,100.56249350309372];

    // HERE IT DOESN"T WORK
    var poly = [];
    for (var j=0;j<lat.length;j++){
        var pos = new google.maps.LatLng(lat[j],lng[j])
        poly.push(pos);
    }

    console.log(poly);

    var Path = new google.maps.Polyline({
        path: poly,
        geodesic: true,
        strokeColor: '#ff004c',
        strokeOpacity: 1.0,
        strokeWeight: 5
    });
    Path.setMap(map);