在javascript中为google maps api访问数组内部的数组

时间:2014-11-17 15:12:12

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

我试图访问数组内部的数组,以便将坐标与Google地图的标记结合起来。 path()函数需要一个google.maps.LatLng(lat,lng)数组来绘制polylinegoogle.maps.Marker对象(?)需要坐标,其他一些东西和文本字符串作为标题。我现在的想法是有一个包含坐标和标题字符串的二维数组。但是,我不能让路径函数接受我的二维数组中的坐标。

var destinations = [
  [new google.maps.LatLng(52.238942,7.349558),'Somewhere'],
  [new google.maps.LatLng(25.073858,55.2298444), 'Dubai'],
  [new google.maps.LatLng(13.7246005,100.6331108), 'Bangkok'],
];

var flightPath = new google.maps.Polyline({
  path: destinations[0],
  geodesic: true,
  strokeColor: '#FF0000',
  strokeOpacity: 1.0,
  strokeWeight: 2
});

非常感谢, Klayman

1 个答案:

答案 0 :(得分:2)

而不是使用LatLng构造函数,您可以将该折线传递给LatLngLiterals数组,该数组可以随意添加额外的键。

        map = new google.maps.Map(document.getElementById('map-canvas'), {
            zoom: 3,
            center: {lat: 20, lng: 63}
        });

        var destinations = [
            {lat:52.238942, lng:7.349558,    title:'Somewhere'},
            {lat:25.073858, lng:55.2298444,  title: 'Dubai'},
            {lat:13.7246005,lng:100.6331108, title: 'Bangkok'},
        ];

        var flightPath = new google.maps.Polyline({
          path: destinations,
          geodesic: true,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2,
          map:map
        });

顺便说一句,您将第一个目的地作为路径传递,而是应该传递整个集合(折线需要一个顶点数组)。其次,您的折线缺少map参数,以便在地图上绘制。