谷歌地图-不知道为什么我总是得到第一个信息窗口

Google maps - not sure why I am always getting the first infowindow

本文关键字:第一个 信息 信息窗 窗口 不知道 为什么 谷歌地图      更新时间:2023-09-26

我有以下代码,每次单击其中一个标记,我都会得到第一个信息窗口。我有181个信息窗口和181个标记。感谢您的帮助。

var i=0;
$.each(in_locations,function(k,v){
  console.log(v);
  var marker_latlng = new google.maps.LatLng(v.latitude, v.longitude);

   markers[i] = new google.maps.Marker({
     position: marker_latlng,
     map: map, 
     title:"here is my title" + v.id
   });

   infowindows[i] = new google.maps.InfoWindow({
     content: "here is some content string" + v.id,
   });
  google.maps.event.addListener(markers[i], 'click', function() {
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
    infowindows[i].open(map,markers[i]);
  });
  i++;
});

thx

警报是否告诉您值始终为181?您需要将处理程序声明包装在一个闭包中,以使用i的外部值来停止它(一旦循环完成,它将始终为181)

  (function(i){
    google.maps.event.addListener(markers[i], 'click', function() {
      alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
      infowindows[i].open(map,markers[i]);
    });
  }(i));

编辑:因为你使用的是jQuery的$.each函数,它为每个迭代提供了自己的范围(因为每个迭代都在调用一个函数),所以你也可以通过创建一个局部变量来解决这个问题,比如j,它获取i的外部值。

  var j = i;
  google.maps.event.addListener(markers[i], 'click', function() {
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + j);
    infowindows[j].open(map,markers[j]);
  });

(这是因为每次迭代都会创建一个新的j,而之前只有1个i,因为您在迭代函数之外声明了它。)

更新

  • 演示:http://jsbin.com/obunap/5
$.each(in_locations, function(i, item){
  console.log(i);
  var marker_latlng = new google.maps.LatLng(item.latitude, item.longitude);

   var markers = new google.maps.Marker({
     position: marker_latlng,
     map: map, 
     title:"here is my title" + item.id
   });

   var infowindows = new google.maps.InfoWindow({
     content: "here is some content string" + item.id,
   });
  google.maps.event.addListener(markers, 'click', function() {
    alert('number of infowindows: ' + in_locations.length + ' and value is: ' + i);
    infowindows.open(map, markers);
  });
});
  • 解释您已经处于循环$.each中,因此不需要增加i++迭代器