为循环添加变量js

时间:2015-06-26 12:35:13

标签: javascript google-maps for-loop

我试图遍历一些坐标集来在Google地图上绘制矢量,但似乎无法正确使用语法以便在以下情况下使用坐标:

False

它告诉我线路路径:buildingCoords [i]应该工作,如果我将它改为路径,它会正确获取第一组:buildingCoords1。我得到的错误信息是

  

未捕获的ReferenceError:未定义buildingCoords

我怎样才能正确追加“我'变量来获取我的坐标。

非常感谢

2 个答案:

答案 0 :(得分:1)

通过使用buildingCoords,您可以引用未定义的变量。添加以下行可以解决您的问题:

var buildingCoords = [buildingCoords1,buildingCoords2];

答案 1 :(得分:0)

  1. 代码中没有buildingCoords数组。正如SimonR所说,你需要创建var buildingCoords = [buildingCoords1,buildingCoords2];

  2. 您只有两个数组,for (i = 1; i < 3; i++)没有意义,应该是for (i = 0; i < buildingCoords.length; i++)

  3. working fiddle

    代码段

    &#13;
    &#13;
    var geocoder;
    var map;
    
    function initialize() {
      var map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(51.49609, -0.27609),
          zoom: 17,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      var buildingCoords1 = [
        new google.maps.LatLng(51.49609, -0.27609),
        new google.maps.LatLng(51.49604, -0.27502),
        new google.maps.LatLng(51.49586, -0.27504),
        new google.maps.LatLng(51.49588, -0.27533),
        new google.maps.LatLng(51.49563, -0.27537),
        new google.maps.LatLng(51.49568, -0.2764),
        new google.maps.LatLng(51.49585, -0.27637),
        new google.maps.LatLng(51.49584, -0.27613)
      ];
    
      var buildingCoords2 = [
        new google.maps.LatLng(51.49548, -0.27586),
        new google.maps.LatLng(51.49504, -0.27593),
        new google.maps.LatLng(51.4951, -0.27701),
        new google.maps.LatLng(51.49555, -0.27695)
      ];
      var buildingCoords = [buildingCoords1, buildingCoords2];
      // plot and add listeners to buildings 1 through 2
      var buildings = [];
      for (i = 0; i < buildingCoords.length; i++) {
    
        buildings[i] = new google.maps.Polygon({
          path: buildingCoords[i],
          strokeColor: '#fccf25',
          strokeOpacity: 0.8,
          strokeWeight: 1,
          fillColor: '#fccf25',
          fillOpacity: 0.35
        });
    
        buildings[i].setMap(map);
    
      } //end for
    }
    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>
    &#13;
    &#13;
    &#13;