将值传递给google.maps.LatLng

时间:2011-12-11 22:29:17

标签: javascript google-maps-api-3

我有一个数组,我想将其值传递给绘制多边形的路径

var coords = new Array("25.1, 66", "25.5, 65", "21.3, 67");

无论坐标号如何,我如何将上述数组中的“x,y”模式传递给google.maps.LatLng

  var triangleCoords = [ 
            new google.maps.LatLng(coords[0]),
             new google.maps.LatLng(coords[1]),
              new google.maps.LatLng(coords[2]),

  ];

  // Construct the polygon
  // Note that we don't specify an array or arrays, but instead just
  // a simple array of LatLngs in the paths property
  draw = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35
  });

2 个答案:

答案 0 :(得分:0)

试试这个:

var coords = new Array("25.1, 66", "25.5, 65", "21.3, 67");
var triangleCoords = [];
for (var i = 0; i < coords.length; i++) {
 var pos = coords[i].split(",");
 var loc = new google.maps.LatLng(pos[0], pos[1]);
  triangleCoords.push(loc);
}

答案 1 :(得分:0)

而不是new google.maps.LatLng(coords[0]),您可以new google.maps.LatLng(coords[0].split(',')[0],coords[0].split(',')[1])

然而,由于那次分裂两次,我可能会把它拉成一个函数 - 就像这样:

function createLatLng(coordString) {
     var a = coordString.split(',');
     return new google.maps.LatLng(a[0],a[1]);
}

var triangleCoords = [ 
       createLatLng(coords[0]),
      ....
];

要获得额外的功劳,您可以使用for循环:

   var triangleCoords = [];
   for (var i = 0; i < coords.length; i++) {
      triangleCoords[i] = createLatLng(coords[i]);
   }