未捕获的InvalidValueError:不是数组

Ton*_*ony 6 javascript php mysql jquery google-maps

我想知道是否有人可以指出我正确的方向,我正在使用Google地图试图为用户设置指定的邮政编码区域,如果我硬编码它的经度经度就像这样完美;

var triangleCoordsLS12 = [
        {lng: -1.558585,  lat: 53.796545}, 
        {lng: -1.558585,  lat: 53.796545},
        .....
];
Run Code Online (Sandbox Code Playgroud)

但是我试图从PHP数据库获取PHP和JSON这样的信息;

$.ajax({
          type:'POST',
          url:'test.php',
          success:function(data){
             var resultArray = JSON.parse(data);
               for (var i=0; i<resultArray.length; i++) {
                  var triangleCoordsLS12 = new google.maps.LatLng(resultArray[i].lat, resultArray[i].lng);

          if(location.uname == 'John Smith'){
            bermudaTriangleLS12 = new google.maps.Polygon({
                paths: triangleCoordsLS12,
                strokeColor: '#ff0000',
                strokeOpacity: 0.8,
                strokeWeight: 1,
                fillColor: '#ff0000',
                fillOpacity: 0.30
            });
           bermudaTriangleLS12.setMap(map);
        } else if(location.uname == 'Bruce Brassington'){
             bermudaTriangleLS12 = new google.maps.Polygon({
               paths: triangleCoordsLS12,
               strokeColor: '#FFcc00',
               strokeOpacity: 0.8,
               strokeWeight: 1,
               fillColor: '#FFcc00',
               fillOpacity: 0.25
             });
            bermudaTriangleLS12.setMap(map);                 
        }
      } 
    }
 })  
Run Code Online (Sandbox Code Playgroud)

Uncaught InvalidValueError: not an Array在这些方面遇到错误: -

bermudaTriangleLS12 = new google.maps.Polygon({
Run Code Online (Sandbox Code Playgroud)

我知道错误说不是Array这样我怎么把点放在数组中?我非常感谢你的帮助.

Bob*_*les 4

您需要先构造数组,然后在创建多边形时使用它。在代码中,您在“坐标”循环内创建一个新的多边形,因此您创建的多边形在每个循环上只有一个点。

//build the array
var resultArray = JSON.parse(data);
var triangleCoordsLS12 = []
for (var i=0; i<resultArray.length; i++) {
    triangleCoordsLS12[i] = new google.maps.LatLng(resultArray[i].lat, resultArray[i].lng);
}
//use the array as coordinates
bermudaTriangleLS12 = new google.maps.Polygon({
         paths: triangleCoordsLS12,
         trokeColor: '#ff0000',
         strokeOpacity: 0.8,
         strokeWeight: 1,
         fillColor: '#ff0000',
         fillOpacity: 0.30
});
bermudaTriangleLS12.setMap(map);
Run Code Online (Sandbox Code Playgroud)

伪代码我的例子:

For each coordinate {
    add coordinate to array
}
construct-polygon(coordinate array)
Run Code Online (Sandbox Code Playgroud)

你的代码:

For each coordinate {
    construct-polygon(coordinate)
}
Run Code Online (Sandbox Code Playgroud)