我正在从数组创建谷歌折线,并使用for循环增加数组,但不绘制折线

时间:2015-06-20 14:21:15

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

对于一个更大的问题,这是一个简单的问题形式,我已经将我的问题缩小到我希望得到帮助的这段代码。

我试图给出我从for循环到数组的路径的坐标,数组有值,但折线不是绘图。

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>
function initialize() {
var mapOptions = {
    zoom: 3,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.TERRAIN
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

var flightPlanCoordinates =[];
for (i=0;i<5;i++)
    {
    flightPlanCoordinates[i] = [new google.maps.LatLng(i,i)];

    }


document.getElementById("demo").innerHTML = flightPlanCoordinates;  /*this is just to check if array has values*/
var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 6.0,
    strokeWeight: 2
});

flightPath.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>

1 个答案:

答案 0 :(得分:1)

发布的代码中存在javascript错误:

Uncaught InvalidValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number

在这一行:

flightPlanCoordinates[i] = [new google.maps.LatLng(i,i)];

应该是:

flightPlanCoordinates[i] = new google.maps.LatLng(i,i);

代码段

&#13;
&#13;
function initialize() {
  var mapOptions = {
    zoom: 3,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

  var flightPlanCoordinates = [];
  for (i = 0; i < 5; i++) {
    flightPlanCoordinates[i] = new google.maps.LatLng(i, i);

  }


  document.getElementById("demo").innerHTML = flightPlanCoordinates; /*this is just to check if array has values*/
  var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 6.0,
    strokeWeight: 2
  });

  flightPath.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#map-canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
<div id="demo"></div>
&#13;
&#13;
&#13;