For循环通过数组只显示最后的值,谷歌地图

For loop through Array only shows last value, Google Map

本文关键字:最后的 谷歌地图 显示 循环 数组 For      更新时间:2023-09-26

我想在谷歌地图上放置3个标记。

在JavaScript中,我写的循环如下

var places = ["Bondi Beach", "Coogee Beach", "Cronulla Beach"];
var lat = [-33.890542, -33.923036, -34.028249];
var lng = [151.274856, 151.259052, 151.157507];
var z=0;
for (tot=lat.length; z < tot; z++) {
  var locations = [
      [places[z], lat[z], lng[z]]
    ];
}

然后初始化map

var map;
var markers = [];
function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 10,
    center: new google.maps.LatLng(-33.92, 151.25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var num_markers = locations.length;
  for (var i = 0; i < num_markers; i++) {  
    markers[i] = new google.maps.Marker({
      position: {lat:locations[i][1], lng:locations[i][2]},
      map: map,
      html: locations[i][0],
      id: i,
    });
    google.maps.event.addListener(markers[i], 'click', function(){
      var infowindow = new google.maps.InfoWindow({
        id: this.id,
        content:this.html,
        position:this.getPosition()
      });
      google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
        markers[this.id].setVisible(true);
      });
      this.setVisible(false);
      infowindow.open(map);
    });
  }
}
init();

然而,这个输出只有一个标记(最后一个),我想知道我的循环出了什么问题?

for (tot=lat.length; z < tot; z++) {
  var locations = [
      [places[z], lat[z], lng[z]]
    ];
 }

在这里,每次迭代都覆盖位置数组。将新元素推入数组

var locations = []
for (tot=lat.length; z < tot; z++) {
   locations.push([places[z], lat[z], lng[z]]);
}